Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Updated map-indexed to add start and step to the indexing
(defn map-indexed
"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."
{:added "1.2"}
([f coll] (map-indexed f 0 1 coll))
([f start coll] (map-indexed f start 1 coll))
([f start step coll]
(letfn [(mapi [idx coll]
(lazy-seq
(when-let [s (seq coll)]
(if (chunked-seq? s)
(let [c (chunk-first s)
size (int (count c))
b (chunk-buffer size)]
(dotimes [i size]
(chunk-append b (f (+ idx (* i step)) (.nth c i))))
(chunk-cons (chunk b) (mapi (+ idx (* size step)) (chunk-rest s))))
(cons (f idx (first s)) (mapi (+ step idx) (rest s)))))))]
(mapi start coll))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment