liveBook · Manning

Map

As explained in Clojure: The Essential Reference

map is a Clojure function that applies a function to corresponding elements of one or more collections and returns a lazy sequence of results.

`map` applies a function to elements of one or more sequentially iterable collections. With collections supplied, it returns a lazy sequence of results—not a key-value map. Prefer a function without side effects: laziness does not guarantee that it will be called exactly once per element. section 3.5.2

Its contract depends on how many collections follow the function:

  • `(map f coll)` calls `f` with one element at a time and returns a lazy sequence. section 3.5.2
  • `(map f c1 c2 & colls)` calls `f` with corresponding elements from each collection. `f` must accept that many arguments; results stop at the shortest collection. section 3.5.2
  • `(map f)` returns a transducer instead of processing a collection immediately. section 3.5.2 section 7.2

Transform one collection

`(map - (range 10))` returns `(0 -1 -2 -3 -4 -5 -6 -7 -8 -9)`. section 3.5.2

Combine corresponding elements

`(map str (range 10) ["a" "b" "c"] "hijklm")` returns `("0ah" "1bi" "2cj")`. The three-element vector ends the mapping. section 3.5.2

When the function also needs each element’s position, use `map-indexed`. For example, `(into {} (map-indexed vector [:a :b :c]))` yields `{0 :a, 1 :b, 2 :c}`. section 3.5.2

How Clojure: The Essential Reference covers it

How deep it goes
Details three arity patterns, lazy results, shortest-input termination, and the caveat against relying on once-only side effects.
Examples
Demonstrates negating a range, combining strings from uneven collections, and assigning indices to keywords.
What it assumes
Assumes familiarity with Clojure functions and collections while specifying the required function arity and seqable inputs.
What you can do after
Apply it via Clojure’s map to transform one or several collections, or use its collection-free arity as a transducer.
How it connects
Connects map to map-indexed, transducers, and sequence processing.

Also explained in

Compare how 8 books explain map →

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.