WolframLang: Scan (aka Foreach)
Map but return Null (aka Foreach)
Scan[f, list]
-
Same as
Map
, but returnNull
. 〔see WolframLang: Map Function to List〕Scan
allows the use ofReturn
andThrow
to exit and return a alternative value.xx = {a, {{b,c}, d}, e}; (* map to leafs, but as soon as c is found, exit. *) Scan[ Function[{x}, Print[ x ]; If[x === c, Return[x] ]], xx, {-1} ] (* a b c Null *)
💡 TIP: When to Use Scan
Scan is useful when:
- You want to go over every element, but do not need the return value. In JavaScript known as “foreach”. 〔see JS: Array.prototype.forEach〕
- You want to go over every element, but as soon as a condition is found, exit.
Scan
allows you to map a function to leafs of a tree or other levels of nodes, using levelspec (likeMap
), but as soon as a condition is found, exit.