Skip to content

Instantly share code, notes, and snippets.

@m0smith
Created September 8, 2011 15:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save m0smith/1203637 to your computer and use it in GitHub Desktop.
Save m0smith/1203637 to your computer and use it in GitHub Desktop.
map-indexed with start
(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 coll))
([f start 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) (.nth c i))))
(chunk-cons (chunk b) (mapi (+ idx size) (chunk-rest s))))
(cons (f idx (first s)) (mapi (inc idx) (rest s)))))))]
(mapi start coll))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment