Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I filter elements from a sequence based on indexes

Tags:

clojure

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:

(filter-by-index '(a b c d e f g) '(0 2 3 4)) ; => (a c d e)

My usecase:

(filter-by-index '(c c# d d# e f f# g g# a a# b) '(0 2 4 5 7 9 11)) ; => (c d e f g a b)
like image 428
qollin Avatar asked Oct 12 '11 18:10

qollin


1 Answers

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))))))
like image 188
Jonas Avatar answered Sep 21 '22 18:09

Jonas