Efficient way to perform independent processing of list from IO?
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
mctague@one.net wrote:
Is there a more memory-efficient approach, perhaps exploiting laziness somehow?
The libraries supplied with HBC (*) include a function called readListLazily, which I have taken the liberty to enclose below. Hopefully, it will help you solve the problem. Regards, Thomas Hallgren (*) See http://www.haskell.org/implementations.html ------------------------------------------------------------------------ -- Copyright (c) 1982-1999 Lennart Augustsson, Thomas Johnsson -- See LICENSE for the full license. -- -- Read a list lazily (in contrast with reads which requires -- to see the ']' before returning the list. readListLazily :: (Read a) => String -> [a] readListLazily cs = case lex cs of [("[",cs)] -> readl' cs _ -> error "No leading '['" where readl' cs = case reads cs of [(x,cs)] -> x : readl cs [] -> error "No parse for list element" _ -> error "Ambigous parse for list element" readl cs = case lex cs of [("]",_)] -> [] [(",",cs)] -> readl' cs _ -> error "No ',' or ']'"
participants (2)
-
mctague@one.net -
Thomas Hallgren