liveBook · Manning

Map-indexed

As explained in Clojure: The Essential Reference

map-indexed is a Clojure function that applies a function to each collection element together with its index and returns the results as a lazy sequence or transducer output.

Use `map-indexed` when a transformation needs both a collection element and its position. With a collection, `(map-indexed f coll)` returns a lazy sequence; `f` receives the zero-based index first and the element second. section 3.5.2

Make integer-keyed entries

`(into {} (map-indexed vector [:a :b :c]))` returns `{0 :a, 1 :b, 2 :c}`. Each call to `vector` pairs an index with its element; `into` collects those pairs as a map. section 3.5.2

Number displayed results

`(map-indexed (fn [idx ticket] (format "winner %s: %s" (inc idx) ticket)) ["QA123A3" "ZR2345Z"])` produces `("winner 1: QA123A3" "winner 2: ZR2345Z")`. Increment the index when the display should start at one. section 3.5.2

Unlike `map`, which can take multiple collections, `map-indexed` accepts one collection or just a function. `(map-indexed f)` returns a transducer for use in a transformation pipeline. Because sequence results are lazy, avoid relying on an exact once-only schedule for side effects in `f`. section 3.5.2 section 7.2

How Clojure: The Essential Reference covers it

How deep it goes
Defines the two arities, argument order, lazy result, and transducer form, without detailing implementation internals.
Examples
Builds a map from indexed vector entries and formats numbered lottery winners.
What it assumes
Assumes familiarity with Clojure functions and collections while specifying the index and element arguments.
What you can do after
Apply it via Clojure's map-indexed to pair elements with positions or label results.
How it connects
Connects map-indexed to map, lazy sequences, transducers, and into.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Clojure: The Essential Reference. The section links point to the parts of the book it draws on.