Map¶
Status: Stable
documented, exercised by the test suite and/or worked examples, with no known limitations recorded.
Description¶
Map[f, expr, levelspec]
applies f at the parts of expr selected by levelspec (e.g. {2} for level 2 only, Infinity for every level).
Notes
f /@ expr or Map\[f, expr\] applies f to each element at level 1 of expr, preserving expr's head.Examples (8)¶
Every input below was run against the current Mathilda build and its output recorded.
Basic examples (2)¶
In[1]:= Map[#^2 &, <|"x" -> 3, "y" -> 4|>]
Out[1]= <|"x" -> 9, "y" -> 16|>
In[2]:= Select[<|"a" -> 1, "b" -> 2, "c" -> 3|>, # > 1 &]
Out[2]= <|"b" -> 2, "c" -> 3|>
Applications (6)¶
In[3]:= Map[f, {a, b, c}]
Out[3]= {f[a], f[b], f[c]}
In[4]:= #^2 & /@ {1, 2, 3, 4}
Out[4]= {1, 4, 9, 16}
In[5]:= Map[Reverse, {{1, 2}, {3, 4}}]
Out[5]= {{2, 1}, {4, 3}}
In[6]:= Map[f, {{a}, {b}}, {2}]
Out[6]= {{f[a]}, {f[b]}}
In[7]:= Map[Total, {{1, 2, 3}, {4, 5, 6}}]
Out[7]= {6, 15}
In[8]:= Map[#^2 &, x + y + z]
Out[8]= x^2 + y^2 + z^2
Implementation notes¶
Algorithm. builtin_map applies f to subexpressions of expr at the
levels selected by an optional level-spec (default {1,1}, the immediate
arguments). The recursion map_at_level works bottom-up: for an
EXPR_FUNCTION it first rebuilds the node by mapping into each argument (and the
head too when Heads -> True), then โ if the node's current level is within
[spec.min, spec.max] (negative levels measured against get_depth) โ wraps it
in f[...] and calls evaluate(). Atoms are copied, and tested for membership
of the level range only by their depth.
Level / option parsing. parse_level_spec reads an integer n, {n},
{m,n}, or Infinity; parse_options reads a trailing Heads -> True. A
Rule-headed third argument is treated as an option rather than a level-spec.
Data structures. Pure Expr-tree traversal; new nodes built with
expr_new_function. Map, MapAll, and MapAt all share this module and the
LevelSpec { min, max, heads } struct.
Attributes: Protected.
References¶
See also: Select
- Harold Abelson and Gerald Jay Sussman, Structure and Interpretation of Computer Programs, 2nd ed., ยง2.2.1 (sequence mapping).
- Source:
src/funcprog.c - Specification:
docs/spec/builtins/data-structures.md - Tests:
tests/test_association.c - Tests:
tests/test_catch_throw.c - Tests:
tests/test_compile.c - Tests:
tests/test_compile_assoc.c
Notes & additional examples¶
Notes¶
f /@ expr is the operator shorthand for Map[f, expr]. By default the function
is applied at level 1, i.e. to the immediate elements; a level specification such
as {2} reaches deeper into nested lists. Map works on any expression, not
only List โ the head is preserved while each argument is wrapped by f. Pure
functions (#^2 &) are the idiomatic first argument.