The monad laws

After going a bit through the methods a monad is supposed to support, now we can formally define the monad laws. You already saw that monads are functors and they follow the functor laws. Being explicit is always better, so here we will mix the laws together:

  • Identity law: Doing map over the identity function doesn't change the data—map(x)(i => i) == x. Flat mapping over the unit function also keeps the data the same—x.flatMap(i => unit(i)) == x. The latter basically says that flatMap undoes unit. Using the connection between map, flatMap, and unit we defined earlier, we can derive one of these two rules from the other and vice versa. The unit method can be thought of as the zero element in monoids.
  • The unit law: From the ...

Get Scala Design Patterns - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.