Fight the Future



One Div Zero: Monads are Elephants Part 1の翻訳続き。

Conclusion for Part I(パート1の結論)

Scala monads must have map and flatMap methods. Map can be implemented via flatMap and a constructor or flatMap can be implemented via map and flatten.


flatMap is the heart of our elephantine beast. When you're new to monads, it may help to build at least the first version of a flatMap in terms of map and flatten. Map is usually pretty straight forward. Figuring out what makes sense for flatten is the hard part.


As you move into monads that aren't collections you may find that flatMap should be implemented first and map should be implemented based on it and unit.


In part 2 I'll cover Scala's syntactic sugar for monads. In part 3 I'll present the elephant's DNA: the monad laws. Finally, in part 4 I'll show a monad that's only barely a container. In the meantime, here's a cheat sheet for translating between computer science papers on monads, Haskell, and Scala.


Generic Haskell Scala
M data M a or newtype M a or instance Monad (M a) class M[A] or case class M[A] or trait M[A]
M a M a M[A]
unit v return v new M(v) or M(v)
map f m fmap f m m map f
bind f m m >>= f or f =<< m m flatMap f
join join flatten
do for