Working through Haskell textbook chapters on different monads, I repeatedly get lost when the authors jump from explaining the details of bind and the monad laws to actually using monads. Suddenly, expressions like "running a function in a monadic context", or "to run a monad" pop up. Similarly, in library documentation and in discussions about monad transformer stacks, I read statements that some function "can be run in any choice of monad". What does this "running inside a monad" exactly mean?
There are two things I don't seem to get straight:
- A monad is a type class with functions (
return
,>>=
) and laws. To "run" something inside a monad could thus either mean (a) to provide it as argument toreturn
, or (b) to sequence it using>>=
. If the monad is of typem a
, then in case a) that something must be of typea
, to match the type of thereturn
function. In case b) that something must be a function of typea -> m b
, to match the type of the>>=
function. From this, I do not understand how I can "run" some function inside an arbitrary monad, because the functions I sequence using>>=
must all have the same type signature, and the values I lift usingreturn
must be of the specific monad type parameter. - In my understanding, there is no notion of execution or running a computation in a functional language - there is only function application to some argument, and evaluating the function (replacing it with its value). Yet, many specific monads come with a
run
function such asrunReader
,runState
, etc. These functions are not part of the definition of a monad, and they are plain functions, not in any way special imperative statements outside the functional core of the language. So, what do they "run"?
I feel that having a clear understanding of these concepts is key to understanding monad transformer stacks or similar constructs that seem to be necessary to understand any substantial libraries and any non-trivial programs in Haskell. Thanks very much for helping me to make the leap from simply writing functional code to actually understanding what it means.
>>=
, I don't need that pattern matching, because it's implicitly done inside>>=
. – Jamey