(map-indexed f)
(map-indexed f coll)
Returns a lazy sequence consisting of the result of applying f to 0
and the first item of coll, followed by applying f to 1 and the second
item in coll, etc, until coll is exhausted. Thus function f should
accept 2 arguments, index and item. Returns a stateful transducer when
no collection is provided.
Source
(defn
map-indexed
"Returns a lazy sequence consisting of the result of applying f to 0\n and the first item of coll, followed by applying f to 1 and the second\n item in coll, etc, until coll is exhausted. Thus function f should\n accept 2 arguments, index and item. Returns a stateful transducer when\n no collection is provided."
([f]
(fn
[rf]
(let
[i (volatile! -1)]
(fn
([] (rf))
([result] (rf result))
([result input] (rf result (f (vswap! i inc) input)))))))
([f coll]
(letfn
[(mapi
[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] (chunk-append b (f (+ idx i) (-nth c i))))
(chunk-cons (chunk b) (mapi (+ idx size) (chunk-rest s))))
(cons (f idx (first s)) (mapi (inc idx) (rest s)))))))]
(mapi 0 coll))))