Efficient way to perform independent processing of list from IO?

[email protected] [email protected]
Wed, 29 Aug 2001 12:07:47 -0600


Hi, I've written a program that reads in a list of things from stdin
and performs an independent computation on each one and prints the
results as a list back to stdout.  I've implemented it as in the
following simple example:

  import IO

  getIntsFromHandle :: Handle -> IO [Int]
  getIntsFromHandle handle =
      do string<-hGetContents handle
	 return (read string)

  writeToHandle :: (Show a)=> a -> Handle -> IO ()
  writeToHandle x handle =
      do hPutStr handle (show x)
	 hClose handle

  main :: IO ()
  main = do ints<-getIntsFromHandle stdin
	 writeToHandle (map (^2) ints) stdout

but with this approach, all the data are read before they are written,
or at least so it seems from memory utilization and by using the
keyboard interactively to type into stdin.  Is there a more
memory-efficient approach, perhaps exploiting laziness somehow?

Thanks,
  Carl