[Haskell-cafe] Lazy Evaluation in Monads

Anthony Cowley acowley at seas.upenn.edu
Tue May 31 22:34:09 CEST 2011


On Tue, May 31, 2011 at 3:49 PM, Scott Lawrence <bytbox at gmail.com> wrote:
> I was under the impression that operations performed in monads (in this
> case, the IO monad) were lazy. (Certainly, every time I make the
> opposite assumption, my code fails :P .) Which doesn't explain why the
> following code fails to terminate:
>
>  iRecurse :: (Num a) => IO a
>  iRecurse = do
>    recurse <- iRecurse
>    return 1
>
>  main = (putStrLn . show) =<< iRecurse
>
> Any pointers to a good explanation of when the IO monad is lazy?

import System.IO.Unsafe

iRecurse :: (Num a) => IO a
iRecurse = do
  recurse <- unsafeInterleaveIO iRecurse
  return 1

More interesting variations of this leave you with questions of
whether or not the missles were launched, or, worse yet, was data
actually read from the file handle?

Anthony



More information about the Haskell-Cafe mailing list