Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Some questions about monads in Haskell

Tags:

haskell

monads

I'm learning about monads and have a few questions.

This is where I am right now. Please correct me where I am wrong.

  • The >>= symbol is an infix operator. Infix operators are functions that take two arguments (left-hand side and right-hand side) and return a value.

  • The >>= symbol is called the bind operator and has signature Monad m => m t -> (t -> m u) -> m u. However, the types don't seem to line up here. We get a value of type m t and the second argument is a function that takes a t. (I don't see how to connect the dots.)

  • This must mean that the bind function is somehow able to remove the m from the m t in order to get the t and pass it to the function.

Here are my questions:

  • Is the ability to remove the m from m t something that is only possible inside such a bind operator. Does this bind operator have some special priviliges or something?

  • What does it have to do with state changes? I understand (I think) that the goal of monads is to 'wrap' side-effects so that they are isolated from the rest of the program. But what is the role of the bind operator in this?

like image 680
StackedCrooked Avatar asked Oct 25 '09 16:10

StackedCrooked


1 Answers

is the ability to remove the 'M' from 'M t' something that is only possible inside such a bind operator.

Well, it is certainly possible inside the bind operator, as its type specifies:

(>>=) :: m a -> (a -> m b) -> m b

The 'run' function for your monad can usually do this as well (to return a pure value from your computation).

the goal of monads is to 'wrap' side-effects so that they are isolated from the rest of the program

Hmm. No, monads let us model notions of computation. Side-effecting computations are just one such notion, as is state, backtracking, continuations, concurrency, transactions, optional results, random results, revertable state, non-determinism ... all of which can be described as a monad

The IO monad is what you're referring to, I assume. It is a slightly odd monad -- it generates sequences of abstract changes to the world's state, which are then evaluated by the runtime. Bind just lets us sequence things in the right order in the IO monad -- and the compiler will then translate all these sequenced world-modifying actions into imperative code that changes that state of the machine.

That's very specific to the IO monad though, not monads in general.

like image 103
Don Stewart Avatar answered Sep 28 '22 03:09

Don Stewart