[Haskell-cafe] Remember the future

Dan Piponi dpiponi at gmail.com
Fri Aug 17 18:10:03 EDT 2007


On 8/17/07, Andrew Coppin <andrewcoppin at btinternet.com> wrote:
> I've seen comments in various places that monads allow you to "borrow
> things from the future".
>
> That sounds completely absurd to me... can anybody explain?

Suppose you buy into the notion that monads sequence actions. Then
consider the following code:

> import Control.Monad.State

> test = do
>     put $ x+1
>     x <- return 1
>     return undefined

> go = execState test undefined

execState runs a sequence of actions in the state monad, ignoring the
returned value and simply giving you back the resulting state. So work
through what this code does:

It sets the value of the state to be 1+x. It then sets x to be 1. And
then it returns undefined. We don't care about the return value, we
just care about the state. And clearly the state is 2. But if you
believe all that action sequencing stuff, we set the state using x
before we actually set the value of x. So we're reading from the
future.

But you can breathe a sigh of relief because the above code doesn't
compile and the laws of physics remain unharmed.

Except...you can switch on ghc's special time travel features using
the -fglasgow-exts flag. Use the time-travel compatible mdo instead of
do and you'll find that this compiles and runs fine:

> import Control.Monad.State
> import Control.Monad.Fix

> test = mdo
>     put $ x+1
>     x <- return 1
>     return undefined

> go = execState test undefined
--
Dan


More information about the Haskell-Cafe mailing list