function | since v0.0-927 | clojure.core/map-indexed | Edit |
(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.
Function f
should accept 2 arguments, index and item.
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.
(defn map-indexed
([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))))