Wolfram: Scan (foreach)
Map but return Null (aka Foreach)
Scan[f, list]-
Same as
Map, but returnNull. [see Wolfram: Map Function to List]Scanallows the use ofReturnandThrowto 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.
Scanallows 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.