|
|
|
|
|
by crdrost
2712 days ago
|
|
`flat` and `flatMap` are highly welcome additions for me; concatenating a bunch of lists together has historically been a very common operation for me, that right now is done best as [].concat(...arrayOfArrays)
It is also the basis more generally for the list monad, where `.flat()` is the `join` operation and `.flatMap()` is the equivalent `bind` operation.So, like, the simplest example is if you're just getting a bunch of results from a paginated source -- you want to flatten them, and it is really nice to just have a method for that. The list monad case is more interesting because it gives a syntax for list comprehensions: [ x + y for x in list1 for y in list2 if x % 2 == 0 and y % 2 == 1 ]
becomes list1.flatMap(x =>
x % 2 !== 0 ? [] : list2.flatMap(y => (y % 2 == 0 ? [] : x + y))
);
And more theoretically this list monad is all about composing nondeterminism, where one input could produce any of N outputs: if you store all of the current possibilities as an array then flatMap is the core composition primitive. |
|