Index filter
Clojure already has a function called filter
. You pass it a predicate and it calls the predicate on each element. But what it doesn't have is a function called filter-index
that calls a predicate on the indexes of the sequence to decide what to keep.
Examples
(filter-index even? "abcdefg") ;=> (\a \c \e \g) (keep even-indexed elements)
(filter-index prime? "abcdefghijk") ;=> (\c \d \f \h) (keep prime-number indexes)
Thanks to this site for the challenge idea where it is considered Hard in Python. The problem has been modified from the original.
Please submit your solutions as comments on this gist.
And in Python:
Edit: as pointed out by @steffan-westcott, the Clojure impl above is broken, because it eats all nils in
coll
. Here's a correct impl:Implements a transducer-returning arity, and uses
clojure.core/sequence
to get the chunked laziness for free.Edit2: Of course, we can use
map-indexed
withvector
, but the above impl avoids the overhead of creating one vector per element: