The first case you describe is an instance of map
pattern, and the second -- flatMap
.
Seen otherwise, map
is just like a loop, and flatMap
is like a two-level nested loops, creating the result's elements one by one from the deepest level loop:
Map:
for x in [1, 2, 3]:
let res = { result of replacing
the first `null` with `x`
in [a, null, c, d, e] }
yield res
-------------------------
[a, null, c, d, e]
----------------------
1 [a, 1, c, d, e],
2 [a, 2, c, d, e],
3 [a, 3, c, d, e]
flatMap:
for x in [1, 2, 3]:
let res = { result of replacing
the first `null` with `x`
in [a, null, c, null, e] }
for x in [1, 2, 3]:
let res2 = { result of replacing
the first `null` with `x`
in res } ## res NB!
yield res2
-------------------------
[ a, null, c, null, e ]
-------------------------
1: [ a, 1, c, null, e ],
1 [a, 1, c, 1 , e],
2 [a, 1, c, 2 , e],
3 [a, 1, c, 3 , e],
2: [ a, 2, c, null, e ],
1 [a, 2, c, 1 , e],
2 [a, 2, c, 2 , e],
3 [a, 2, c, 3 , e],
3: [ a, 3, c, null, e ]
1 [a, 3, c, 1 , e],
2 [a, 3, c, 2 , e],
3 [a, 3, c, 3 , e]
The first is like replacing each element in [1,2,3]
with the replacement result; and the second is like replacing each element in [1,2,3]
with the list of the replacement results and appending the resulting lists together; i.e. splicing the resulting lists' elements in place; i.e. creating the combined map, flattened (hence the name, flatMap
).