3
$\begingroup$

I'm learning about monads, I understood why they are useful, I understood in general what bind, join, return do.

I also looked at basic usage examples for the basic reader / writer / state / list / maybe monads.

Still, being a beginner, I still don't feel I have a grip on what the "run" function means in general. It does not seem to have a generic signature like the above functions, and I don't get it if it's definable / makes sense for all monads.

$\endgroup$
2
$\begingroup$

Short answer:

There isn't a run-function for all monads, and its use is evaluating data structures.

Medium answer:

Certain monads build data structures that will be evaluated afterwards. Let's say we want to build our own IO monad (I'll need to use GADT notation, basically I just talk about inhabitants and their specific types):

data SimpleIO a where
  PutStr :: String -> SimpleIO ()
  GetLine :: SimpleIO String
  Bind :: SimpleIO a -> (a -> SimpleIO b) -> SimpleIO b
  Return :: a -> SimpleIO a

Like this, we can build a few IO actions, like one that just reads a string and prints it: Bind GetLine PutStrdoes exactly that. However, our monad doesn't do anything: We don't know how to execute those actions, so we need some kind of conversion function:

runSimpleIO :: SimpleIO a -> IO a
runSimpleIO (PutStr x) = putStrLn x
runSimpleIO GetLine = getLine
runSimpleIO (Bind x f) = x >>= f
runSimpleIO (Return x) = return x

This is some kind of run function, it uses the monad-made structure to make use of it. It definitely isn't unique though: You might as well write a run function SimpleIO a -> Maybe a. That's nothing defined within the monad, but more of an interpretation.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.