Doing IO in foldr repeats lines?
Scott Turner
p.turner@computer.org
Sat, 20 Jan 2001 17:08:48 -0500
At 21:17 2001-01-20 +0000, Ian Lynagh wrote:
> main = do _ <- foldl foo (return 14) ["qq\n", "ww\n", "ee\n"]
> putStr ""
>
> foo :: IO Int -> String -> IO Int
> foo io_l s = do l <- io_l
> () <- putStr s
> io_l
It repeats lines
>and I really don't understand why. Is the code re-evaluated every time
>foldl is expanded or something?
Since the result type of foo is IO Int, it is building an IO action, in
other words it is calculating a sequence of effects. The combined effects
are performed by main.
Repetition occurs due to the structure of foo. Notice that its action
consists of first performing io_l, then putting a string, and then
performing io_l _again_. If io_l prints the lines qq, ww, and qq, then the
result will involve two such triplets.
Try this. Remove either of the occurrences of io_l from the do block, and
you will see quite different results.
--
Scott Turner
p.turner@computer.org http://www.billygoat.org/pkturner