[Haskell] Laziness and the IO Monad (randomness)
Joe Thornber
joe.thornber at gmail.com
Fri Mar 2 08:21:37 EST 2007
On 01/03/07, Dave Tapley <dukedave at gmail.com> wrote:
> My question asks why this is the case, when laziness should ensure only the
> first 10 cases need to be computed.
Just to clarify some of the other answers you've got. Saying the IO
monad is strict isn't the whole picture, after all 'do {txt <-
getContents; putStrLn $ transform txt}' doesn't read all the contents
in before transforming it.
The reason your program hangs is that you are trying to return an
infinite list generated from an _infinite sequence of IO actions_.
This example might help:
> getList1, getList2, getList3 :: IO [Int]
> getList1 = return . repeat $ 0
> getList2 = do {lst <- getList2; return $ 0 : lst}
> getList3 = sequence . repeat . return $ 0
> main = do
> lst <- getList1
> putStrLn . show . take 10 $ lst
getList1 will work in the lazy way that you expected. getList2 and
getList3 are equivalent to each other and similar to your iterateM,
they will loop forever.
I hope this helps,
- Joe
More information about the Haskell
mailing list