WolframLang: Map Function to List

By Xah Lee. Date: . Last updated: .
Map[f, list]

🔸 SHORT SYNTAX: f /@ list

Apply a function to each element, return the result list.

Map

(* Map a function to list *)

Map[ f, {3,4,5} ]
(* {f[3], f[4], f[5]} *)

(* short syntax *)
f /@ {3,4,5}
(* Map a user-defined function to list *)

Map[
Function[x, x+1 ],
{1, 2, 3}
]

(* {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.

If levelSpec is negative, count from leafs.

💡 TIP: one great use is map to leafs of a tree by using levelSpec -1.

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} *)
xx = {a, {{b,c}, d}, e};

(* map to leafs *)
Map[ f, xx, {-1} ]
(* {f[a], {{f[b], f[c]}, f[d]}, f[e]} *)

Map but return Null

Scan[f, list]

Same as Map, but return Null.

Scan allows the use of Return and Throw to return a alternative value and exit.

Scan

Map with Index

MapIndexed

Like Map, but also feed the index to the function.

💡 TIP: Useful when you want to go over array but also need the index.

The function receive 2 args, first is value, second is the Position spec of the value.

MapIndexed

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).

MapThread

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]} *)

WolframLang Loop, Iteration, Recursion

WolframLang List