[Haskell] threading mutable state through callbacks

Adrian Hey ahey at iee.org
Tue Oct 12 18:00:19 EDT 2004

On Tuesday 12 Oct 2004 8:43 pm, Vincenzo Ciancia wrote:
> The objection was for cases like
> x :: Int <- someIOAction
> y :: Int = x + 1
> Note that both have Int type but the second is a pure value while the
> first is the result of a computation.

Well obviously if people are going to use it stupidly (I.E. the value
returned by someIOAction is dependent on when it occurs) that might be
a bug. But there's really no guarantee of "sane" behaviour with
anything that's done in the via the IO monad (finalisers, forkIO..),
other than what the programmer ensures by writing bug free code.
So I dunno why we should insist on higher standards of sanity in
this case.

But there is a real fundamental problem with the only current
alternative (use of wierd library non-functions like unsafePerformIO),
in that the compiler itself cannot be relied upon to interpret the
program correctly and generate the code the programmer intended (at
least not unless the programmer understands the dangers and supplies
necessary flags & pragmas).

If I have..

myThing      = unsafePerformIO newThing
myOtherThing = unsafePerformIO newThing

Then conventional referential transparency means that the compiler
should be able to freely interchange (myThing),(myOtherThing) and
(unsafePerformIO newThing) anywhere it likes. Clearly a problem
if they're IORefs or similar.

By adding something like the myThing <- newThing at the top level
this danger could be eliminated. Certainly abuse is still possible,
but I don't care about that. (If some folk want to be that stupid
it's fine with me :-)

> I think that the easy way would be to allow a keyword like a top-level
> let, where a program like
> let x1 <- action1
> ...
> let xn <- actionn
> main = other_actions
> is equivalent to
> main = do
>  x1 <- action1
>  ...
>  xn <- actionn
>   other_actions
> top-level "ordinary" bindings can't see x1...xn, and order of evaluation
> is imposed.

Unfortunately, in this case the whole point of what people are trying to
do with unsafePerformIO is to allow these things to be visible at the top
level :-)

Adrian Hey

More information about the Haskell mailing list