(keep-indexed f)
(keep-indexed f coll)
Returns a lazy sequence of the non-nil results of (f index item). Note,
this means false return values will be included. f must be free of
side-effects. Returns a stateful transducer when no collection is
provided.
Source
(defn
keep-indexed
"Returns a lazy sequence of the non-nil results of (f index item). Note,\n this means false return values will be included. f must be free of\n side-effects. Returns a stateful transducer when no collection is\n provided."
([f]
(fn
[rf]
(let
[ia (volatile! -1)]
(fn
([] (rf))
([result] (rf result))
([result input]
(let
[i (vswap! ia inc) v (f i input)]
(if (nil? v) result (rf result v))))))))
([f coll]
(letfn
[(keepi
[idx coll]
(lazy-seq
(when-let
[s (seq coll)]
(if
(chunked-seq? s)
(let
[c (chunk-first s) size (count c) b (chunk-buffer size)]
(dotimes
[i size]
(let
[x (f (+ idx i) (-nth c i))]
(when-not (nil? x) (chunk-append b x))))
(chunk-cons (chunk b) (keepi (+ idx size) (chunk-rest s))))
(let
[x (f idx (first s))]
(if
(nil? x)
(keepi (inc idx) (rest s))
(cons x (keepi (inc idx) (rest s)))))))))]
(keepi 0 coll))))