How do I filter elements from a sequence based on indexes

后端 未结 8 1934
慢半拍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条回答
  •  旧时难觅i
    2021-02-19 11:00

    I like Jonas's answer, but neither version will work well for an infinite sequence of indices: the first tries to create an infinite set, and the latter runs into a stack overflow by layering too many unrealized lazy sequences on top of each other. To avoid both problems you have to do slightly more manual work:

    (defn filter-by-index [coll idxs]
      ((fn helper [coll idxs offset]
         (lazy-seq
          (when-let [idx (first idxs)]
            (if (= idx offset)
              (cons (first coll)
                    (helper (rest coll) (rest idxs) (inc offset)))
              (helper (rest coll) idxs (inc offset))))))
       coll idxs 0))
    

    With this version, both coll and idxs can be infinite and you will still have no problems:

    user> (nth (filter-by-index (range) (iterate #(+ 2 %) 0)) 1e6)
    2000000
    

    Edit: not trying to single out Jonas's answer: none of the other solutions work for infinite index sequences, which is why I felt a solution that does is needed.

提交回复
热议问题