1.3.0 permalink Arrow_down_16x16

map-indexed

clojure.core

  • (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.

2 Examples top

  • user=> (map-indexed (fn [idx itm] [idx itm]) "foobar")
    ([0 \f] [1 \o] [2 \o] [3 \b] [4 \a] [5 \r])
    
    
  • ;; or simply
    user=> (map-indexed vector "foobar")
    ([0 \f] [1 \o] [2 \o] [3 \b] [4 \a] [5 \r])
Log in to add / edit an example.

See Also top

Log in to add a see also.

Plus_12x12 Minus_12x12 Source clojure/core.clj:6312 top

(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"
   :static true}
  [f 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 0 coll)))
Vars in clojure.core/map-indexed:
Used in 0 other vars

Comments top

No comments for map-indexed. Log in to add a comment.