[Haskell-cafe] Can we come out of a monad?
dagit at codersbase.com
Fri Jul 30 03:04:29 EDT 2010
On Thu, Jul 29, 2010 at 11:48 PM, Lyndon Maydwell <maydwell at gmail.com>wrote:
> You cannot break out of a monad if all you have available to use are
> the monad typeclass functions, however there is nothing preventing an
> instance from being created that allows escape. Many of these escape
> methods come in the form of runX functions, but you can use
> constructors to break out with pattern matching if they are exposed.
There is one case where you can break out of a monad without knowing which
monad it is. Well, kind of. It's cheating in a way because it does force
the use of the Identity monad. Even if it's cheating, it's still very
clever and interesting.
<http://okmij.org/ftp/Computation/lem.html>The specific function is:
> purify :: (forall m. Monad m => ((a -> m b) -> m b)) -> ((a->b)->b)
> purify f = \k -> runIdentity (f (return . k))
We take some arbitrary monad 'm' and escape from it. Actually, the trick is
that f must work for ALL monads. So we pick just one that allows escape and
apply f to it. Here we picked Identity. You could have picked Maybe,
lists, and any of the others that allow escaping.
> As far as I can tell, IO is more of an outlier in this regard.
Yes I agree there. And even with IO we have unsafePerformIO that lets you
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the Haskell-Cafe