day 4里面粗看了typeclass law以及一些Monoid。今天就到了Monads

Monads are a natural extension applicative functors, and they provide a solution to the following problem: If we have a value with context, m a, how do we apply it to a function that takes a normal a and returns a value with a context.

Scalaz提供了Monad。（Oh， the M word， Scala）。

Bind

Bind的代码是这样的。

Walk the line

Let’s say that [Pierre] keeps his balance if the number of birds on the left side of the pole and on the right side of the pole is within three. So if there’s one bird on the right side and four birds on the left side, he’s okay. But if a fifth bird lands on the left side, then he loses his balance and takes a dive.

Banana on wire

We may also devise a function that ignores the current number of birds on the balancing pole and just makes Pierre slip and fall. We can call it banana.

for syntax

Haskell中，Monad有一个明显的好处，就是可以直接使用do这种语法糖。而在Scala中，使用的是for语句。

Pattern matching and failure

On the other hand, a value like [3,8,9] contains several results, so we can view it as one value that is actually many values at the same time. Using lists as applicative functors showcases this non-determinism nicely.

List可以看做用来描述non-determinismMonad

scalafor可以添加filtering

The MonadPlus type class is for monads that can also act as monoids.

Scalaz中的MonadPlus

Plus, PlusEmpty, and ApplicativePlus

Semigroup[A]以及Monoid[A]相似，Plus[F[_]]以及PlusEmpty[F[_]]需要去实现plus以及empty，但是是在F[_]这个类型构造器的层次上。

Plus引入了<+>去连接两个containers

A knight’s quest

Here’s a problem that really lends itself to being solved with non-determinism. Say you have a chess board and only one knight piece on it. We want to find out if the knight can reach a certain position in three moves.

Monad也像functor等一样，Monad Laws有着重要的地位。

Left identity

if we take a value, put it in a default context with return and then feed it to a function by using >>=, it’s the same as just taking the value and applying the function to it.

Right identity

if we have a monadic value and we use >>= to feed it to return, the result is our original monadic value.

Associativity

when we have a chain of monadic function applications with >>=, it shouldn’t matter how they’re nested.

Scalaz里面，这样描述这些Law