F2.05 · part 1 of 4
map
Map applies one function to every element and collects the results. The output has the same length as the input and the same order — one element in, one element out. It transforms contents without touching shape.
Because each element is handled independently, map says nothing about order of effects and
everything about the transformation. That independence is also why two maps in a row collapse into one: doing
f then g to every element is the same as doing
g(f(x)) once.
One function, every element
Hand map a function and it runs that function over each element, building a new list of the results. The input is untouched; the output is the same size. Swap the function and the same call transforms differently.
Choose the function map applies.
- map
- apply a function to every element, collecting the results in order.
- transform
- the per-element function map runs; the part that varies.
- one to one
- each element produces exactly one result — length is preserved.
- Enum.map
- Elixir’s map:
Enum.map(list, fun).
Enum.map · one in, one out
Idea
Transform contents, preserve shape: same count, same positions.
F2.05 · reduce
Map is reduce with a list accumulator that appends each transformed element.
Map changes every element the same way and keeps the list’s size and order. The function is the only thing that varies.
Chained maps fuse
Map one function, then map another, and you have walked the list twice. But mapping
f then g gives the same result as mapping the single
function x → g(f(x)) once. The two passes fuse into one.
Compare two passes against the fused map.
map(&1 * 2) then map(&1 + 1)
F1.03 · composition
Mapping a composition equals composing the maps — one walk instead of two.
Elixir
Readable pipelines often keep the two maps; fuse when a pass matters.
Two maps in a row are one map of the composed function. Same result, half the traversals.
Worked examples
Three everyday maps. Each keeps the list’s length; only the per-element value changes.