WolframLang: Map Function to List
Map[f, expr]
-
(Short syntax:
f /@ expr
)
Like many language's map, but can map to specific level of a nested list, such as at leafs of a tree. e.g.Map[ f, {1, {{2}, 3}}, {-1} ] === {f[1], {{f[2]}, f[3]}}
Map Scan[f, expr]
-
Same as
Map
, but returnNull
. use this if you no need return value. Scan
Map a builtin function to list:
xx = {1, {2, 3}}; Map[ Length, xx ] === {0, 2} (* short syntax *) Length /@ xx === {0, 2}
Map a user-defined function to list:
xx = {1, 2, 3}; Map[ Function[x, x+1 ], xx ] === { 2, 3, 4} (* short syntax *) (#+1 &) /@ xx === { 2, 3, 4}
Map a function to different levels of a rectangular array:
(xx = Table[{i, j}, {i, 2}, {j, 2}]) === {{{1, 1}, {1, 2}}, {{2, 1}, {2, 2}}} (* map to 1st level, as in flat map *) Map[ f, xx, {1} ] === {f[{{1, 1}, {1, 2}}], f[{{2, 1}, {2, 2}}]} (* map to 2nd level *) Map[ f, xx, {2} ] === {{f[{1, 1}], f[{1, 2}]}, {f[{2, 1}], f[{2, 2}]}} (* map to 3rd level *) Map[ f, xx, {3} ] === {{{f[1], f[1]}, {f[1], f[2]}}, {{f[2], f[1]}, {f[2], f[2]}}} (* map to deepest level, the leafs. in this case, same as 3rd level *) Map[ f, xx, {-1} ] === {{{f[1], f[1]}, {f[1], f[2]}}, {{f[2], f[1]}, {f[2], f[2]}}}

Map to a tree.
xx = {a, {{b,c}, d}, e}; (* map to top level *) Map[ f, xx ] === {f[a], f[{{b, c}, d}], f[e]} (* same as 1st level *) Map[ f, xx, {1} ] === {f[a], f[{{b, c}, d}], f[e]} (* map to leafs *) Map[ f, xx, {-1} ] === {f[a], {{f[b], f[c]}, f[d]}, f[e]}
Map with Index
MapIndexed
- Like
Map
, but also feed the index to the function. Useful when you want to “iterate” over array but also need the index.The function receive 2 args, first is value, second is the Position spec of the value.
MapIndexed[ f, {a,b,c} ] === {f[a, {1}], f[b, {2}], f[c, {3}]}
MapIndexed
Map for function with multiple parameters
MapThread
- Like
Map
, but for functions that take more than 1 arg.xx = {{1, 2, 3} , {a, b, c} }; MapThread[ f, xx ] === {f[1, a], f[2, b], f[3, c]}
xx = {{1, 2, 3}, {a, b, c}, {x, y, z} }; MapThread[f, xx] === {f[1, a, x], f[2, b, y], f[3, c, z]}
MapThread