How do I filter elements from a sequence based on indexes

后端 未结 8 1880
慢半拍i
慢半拍i 2021-02-19 10:08

I have a sequence s and a list of indexes into this sequence indexes. How do I retain only the items given via the indexes?

Simple example:

8条回答
  •  天涯浪人
    2021-02-19 10:42

    (defn filter-by-index [seq idxs]
      (let [idxs (into #{} idxs)]
        (reduce (fn [h [char idx]]
                  (if (contains? idxs idx)
                    (conj h char) h))
                [] (partition 2 (interleave seq (iterate inc 0))))))
    
    (filter-by-index [\a \b \c \d \e \f \g] [0 2 3 4])
    =>[\a \c \d \e]
    

提交回复
热议问题