3 ms·
As usual when someone tries to get into explaining monads, mistakes happen. First, on the scala standard library and monads: Scala very carefully avoided creat
by hibikir 11y ago
As usual when someone tries to get into explaining monads, mistakes happen.
First, on the scala standard library and monads: Scala very carefully avoided creating a Monad trait, on purpose. So while List and Options are monads, we can't just go and say that everything that has a flatmap is a monad.
Also, the reason we can combine options and lists in a for comprehension is not really that they both have a flatmap: Try doing that with Future instead, and it will not work quite so easily! The reason those two have such easy interoperability is that in Scala's Predef there is a conversion that turns an Option into a Traversable, which is being called under the covers. For comprehensions are very powerful, but switching from one monadic context to another without help isn't one of them. In the case of Future and List, for instance, we'd have to use some of the utility methods in the Future object that can help transform a future into a List[Future], and a List[Future] into Future[List]
Don't get me wrong, it's great to see people trying to explain this kind of stuff, but it is so very hard to cover the topic in a way that is both approachable and that doesn't leave people with intuitions that will fail them outside of the given example.
- miloszpp 11y ago[Author] Thanks for your remarks. I agree on the first point. As to the second, I didn't mean that having flatmap is the reason why we can combine Options and Lists. I meant that Options are composable with other Options and Lists are composable with other Lists. I understand the problem of working with different monads. I looked into monad transformers at some point and found them difficult to work with so my approach now is to avoid mixing monad types (for example instead of having Future[Option[T]], just use a failed Future instead of None).