4 ms·
By the way, as a simple example of what I mean when I say that monads are the least constrained form of sequencing: flat_map is strictly more general than map.
by howinteresting 4y ago
By the way, as a simple example of what I mean when I say that monads are the least constrained form of sequencing: flat_map is strictly more general than map. In Rust, if an iterator I implements ExactSizeIterator, then Map<I, F> implements ExactSizeIterator:
https://doc.rust-lang.org/std/iter/struct.Map.html#impl-ExactSizeIterator-for-Map%3CI,%20F%3E https://doc.rust-lang.org/std/iter/struct.Map.html#impl-Exac...
However, there is no such implementation for FlatMap<I, F>:
https://doc.rust-lang.org/std/iter/struct.FlatMap.html https://doc.rust-lang.org/std/iter/struct.FlatMap.html
This intuitively makes sense! If a single input can generate zero, one or more than one outputs, then there's no way to know the exact size of it.
The simple map is more constrained -- it has to generate exactly one value -- which means that it can support more operations. The monad-like flat_map is less constrained, and it can do more, which means that it can't support as many operations. There's a catchphrase in the programming language community to describe this sort of thing: "constraints liberate, liberties constrain".
This can make a huge difference in production systems. For example, if you have a distributed system that walks over an execution graph, and nodes in the graph can create new nodes (flat_map/monad-like), the properties of your system are very different from if nodes can't do that.