How do I filter elements from a sequence based on indexes

后端 未结 8 1885
慢半拍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条回答
  • The easiest solution is to use map:

    (defn filter-by-index [coll idx]
      (map (partial nth coll) idx))
    
    0 讨论(0)
  • 2021-02-19 11:05

    You can use keep-indexed:

    (defn filter-by-index [coll idxs]
      (keep-indexed #(when ((set idxs) %1) %2) 
                    coll))  
    

    Another version using explicit recur and lazy-seq:

    (defn filter-by-index [coll idxs]
      (lazy-seq
       (when-let [idx (first idxs)]
         (if (zero? idx)
           (cons (first coll)
                 (filter-by-index (rest coll) (rest (map dec idxs))))
           (filter-by-index (drop idx coll)
                            (map #(- % idx) idxs))))))
    
    0 讨论(0)
提交回复
热议问题