How do I filter elements from a sequence based on indexes

后端 未结 8 1912
慢半拍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:39

    make a list of vectors containing the items combined with the indexes,

    (def with-indexes (map #(vector %1 %2 ) ['a 'b 'c 'd 'e 'f] (range)))
    #'clojure.core/with-indexes
     with-indexes
    ([a 0] [b 1] [c 2] [d 3] [e 4] [f 5])
    

    filter this list

    lojure.core=> (def filtered (filter #(#{1 3 5 7} (second % )) with-indexes))
    #'clojure.core/filtered
    clojure.core=> filtered
    ([b 1] [d 3] [f 5])
    

    then remove the indexes.

    clojure.core=> (map first filtered)                                          
    (b d f)
    

    then we thread it together with the "thread last" macro

    (defn filter-by-index [coll idxs] 
        (->> coll
            (map #(vector %1 %2)(range)) 
            (filter #(idxs (first %)))
            (map second)))
    clojure.core=> (filter-by-index ['a 'b 'c 'd 'e 'f 'g] #{2 3 1 6}) 
    (b c d g)
    

    The moral of the story is, break it into small independent parts, test them, then compose them into a working function.

提交回复
热议问题