WolframLang: Map Function to List
Map[f, list]
-
(Short syntax:
f /@ list
)Apply a function to each element, return the result list.
(* 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 Specific Level of a Tree, or to Leafs
Map[f, list, levelSpec]
-
Apply a function to each element, at specific level or range of levels, specified by levelSpec.
Example: Map to a tree.
(* example of using levelspec in map *) xx = {a, {{b,c}, d}, e}; (* map to 1st level *) Map[ f, xx, {1} ] === {f[a], f[{{b, c}, d}], f[e]} (* map to 2nd level *) Map[ f, xx, {2} ] === {a, {f[{b, c}], f[d]}, e} (* map to 3rd level *) Map[ f, xx, {3} ] === {a, {{f[b], f[c]}, d}, e} (* map to leafs *) Map[ f, xx, {-1} ] === {f[a], {{f[b], f[c]}, f[d]}, f[e]}
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]}}}
WolframLang map to different levels of nesting
Map but return Null
Scan[f, list]
-
Same as
Map
, but returnNull
.
Map with Index
MapIndexed
-
Like
Map
, but also feed the index to the function.💡 TIP: 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}]}
Map for function with multiple parameters
MapThread
-
Like
Map
, but for functions that take 2 args (or more).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]}