Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Lazy IO" in Haskell?

I'm trying a little experiment in haskell, wondering if it is possible to exploit laziness to process IO. I'd like to write a function that takes a String (a list of Chars) and produces a string, lazily. I would like then to be abily to lazily feed it characters from IO, so each character would be processed as soon as it was available, and the output would be produced as the characters necessary became available. However, I'm not quite sure if/how I can produce a lazy list of characters from input inside the IO monad.

like image 576
Edward Avatar asked Feb 18 '10 16:02

Edward


1 Answers

Regular String IO in Haskell is lazy. So your example should just work out of the box.

Here's an example, using the 'interact' function, which applies a function to a lazy stream of characters:

interact :: (String -> String) -> IO ()

Let's filter out the letter 'e' from the input stream, lazily (i.e. run in constant space):

main = interact $ filter (/= 'e')

You could also use getContents and putStr if you like. They're all lazy.

Running it to filter the letter 'e' from the dictionary:

$ ghc -O2 --make A.hs
$ ./A +RTS -s < /usr/share/dict/words
...
               2 MB total memory in use (0 MB lost due to fragmentation)
...

so we see that it ran in a constant 2M footprint.

like image 79
Don Stewart Avatar answered Oct 04 '22 04:10

Don Stewart