 Continuo da qui, copio qui.

So far we’ve seen two uses of monads. The first use was `IO` actions: We’ve seen that, by using monads, we can get away from the problems plaguing the RealWorld solution to `IO` presented in the chapter IO [qui e post seguenti]. The second use was representing different types of computations in the section on Classes-computations [qui]. In both cases, we needed a way to sequence operations and saw that a sufficient definition (at least for computations) was:

``````class Computation c where
success :: a -> c a
failure :: String -> c a
augment :: c a -> (a -> c b) -> c b
combine :: c a -> c a -> c a``````

Let’s see if this definition will enable us to also perform `IO`. Essentially, we need a way to represent taking a value out of an action and performing some new operation on it (as in the example from the section on Functions-io, rephrased slightly):

``````main = do
putStrLn (show (f s))``````

But this is exactly what augment does. Using augment, we can write the above code as:

``````main =  -- note the lack of a "do"
putStrLn (show (f s))``````

This certainly seems to be sufficient. And, in fact, it turns out to be more than sufficient.

The definition of a monad is a slightly trimmed-down version of our `Computation` class. The `Monad` class has four methods (but the fourth method can be defined in terms of the third):

``````class Monad m where
return  :: a -> m a
fail    :: String -> m a
(>>=)   :: m a -> (a -> m b) -> m b
(>>)    :: m a -> m b -> m b``````

In this definition, `return` is equivalent to our `success`; `fail` is equivalent to our `failure`; and `>>=` (read: “bind” ) is equivalent to our `augment`. The `>>` (read: “then” ) method is simply a version of `>>=` that ignores the `a`. This will turn out to be useful; although, as mentioned before, it can be defined in terms of `>>=`:

`a >> x = a >>= \_ -> x`

Fin qui sembra tutto OK 😋

👽

Posta un commento o usa questo indirizzo per il trackback.