5 ms·
> you want to abstract over it. What does that mean? Any example you could point to?
by _448 4y ago
> you want to abstract over it.
What does that mean? Any example you could point to?
- howinteresting 4y agoAre you familiar with flat_map? It's the ability to take, for example, an iterator, then map over each element which itself can return an iterator. Similarly, you have Option::and_then, which takes a callback that takes T and returns an Option<T>. Or Result::and_then. "Monad" is simply the umbrella term for all flat_maps, and things like it, in existence. Why would you want to abstract over it? For one, it's a surprisingly common design pattern in programming. You also quickly notice, for example, that filter_map is actually just a special case of flat_map since Option implements Iterator. You can also study the properties of how such patterns behave. Monads are particularly interesting for a number of reasons. Monads are a kind of "most general" and least constrained form of sequencing, and it turns out that if your large-scale system is monad-like it can have a significant performance impact! You don't need to have a thing called "Monad" in your type system to do any of the above. Having a thing called "Monad" in your type system does let you write code that abstracts over all flat_maps (and things like it) in existence, which has been used in the Haskell world to build a number of interesting libraries. But "monads" as a concept are useful to everyone in programming.
- howinteresting 4y agoBy 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.