Tasteful stateful computations

Haskell features a thing called the state monad, which makes dealing with stateful problems a breeze while still keeping everything nice and pure.

State and StateT

We’ll say that a stateful computation is a function that takes some state and returns a value along with some new state. That function would have the following type:

Scalaz中的State大概是这个样子的

StateFunctions中还定义了一些辅助函数，

When we were learning about the monad laws, we said that the <=< function is just like composition, only instead of working for normal functions like a -> b, it works for monadic functions like a -> m b.

Kleisli

Scalaz中，这就是那个A => M[B]的封装。

Scalaz中定义通过Kleisli来定义ReaderT

In this section, we’re going to look at an example of how a type gets made, identified as a monad and then given the appropriate Monad instance. … What if we wanted to model a non-deterministic value like [3,5,9], but we wanted to express that 3 has a 50% chance of happening and 5 and 9 both have a 25% chance of happening?