[Haskell-cafe] What unsafeInterleaveIO is unsafe
daniel.is.fischer at web.de
Sun Mar 15 16:43:01 EDT 2009
Am Sonntag, 15. März 2009 21:25 schrieb Jonathan Cast:
> On Sun, 2009-03-15 at 13:02 -0700, Ryan Ingram wrote:
> > Furthermore, due to the monad laws, if f is total, then reordering the
> > (x <- ...) and (y <- ...) parts of the program should have no effect.
> > But if you switch them, the program will *always* print 0.
> I'm confused. I though if f was strict, then my program *always*
> printed 1?
But not if you switch the (x <- ...) and (y <- ...) parts:
main = do
r <- newIORef 0
v <- unsafeInterleaveIO $ do
writeIORef r 1
y <- readIORef r
x <- case f v of
0 -> return 0
n -> return (n - 1)
Now the IORef is read before the case has a chance to trigger the writing.
More information about the Haskell-Cafe