laziness in IO

Hal Daume III hdaume@ISI.EDU
Wed, 8 Jan 2003 10:19:27 -0800 (PST)


The following works for me:

import IOExts

main = do xs <- unsafeInterleaveIO getStrings
          putStrLn (head xs)

getStrings = do
  x <- getLine
  if x == "stop"
    then return []
    else do xs <- unsafeInterleaveIO getStrings; return (x:xs)


in this particular case, the unsafeInterleaveIO on the recursive call to
getStrings isn't necessary, but if you change 'putStrLn (head xs)' to
'mapM_ putStrLn (take 3 xs)' then it's necessary (I believe).

HTH

 - Hal

--
Hal Daume III

 "Computer science is no more about computers    | hdaume@isi.edu
  than astronomy is about telescopes." -Dijkstra | www.isi.edu/~hdaume

On Wed, 8 Jan 2003, Amanda Clare wrote:

> How can I recursively collect a list of things while in the IO monad, 
> and return the list lazily as it's constructed rather than waiting until 
> they've all been collected?
> 
> Perhaps an example will make things clearer:
> 
> 
> main =
>    do xs <- getStrings
>       putStrLn (head xs)
> 
> getStrings =
>    do x <- getLine
>       if x == "stop"
>         then return []
>         else do xs <- getStrings
>                 return (x:xs)
> 
> 
> How can I make getStrings lazy? main should be able to terminate 
> immediately after I've entered just one line.
> 
> Amanda
> 
> ps: This is a fake example, I'm really trying to lazily retrieve answers 
> fetched from an Oracle SQL query.
> 
> _______________________________________________
> Haskell mailing list
> Haskell@haskell.org
> http://www.haskell.org/mailman/listinfo/haskell
>