Search code examples
haskellmonadscomonad

How to extract value from monadic action


Is there a built-in function with signature :: (Monad m) => m a -> a ?

Hoogle tells that there is no such function.

Can you explain why?


Solution

  • A monad only supplies two functions:

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

    Both of these return something of type m a, so there is no way to combine these in any way to get a function of type Monad m => m a -> a. To do that, you'll need more than these two functions, so you need to know more about m than that it's a monad.

    For example, the Identity monad has runIdentity :: Identity a -> a, and several monads have similar functions, but there is no way to provide it generically. In fact, the inability to "escape" from the monad is essential for monads like IO.