I understand that I should not try to re-read from stdin because of errors about Haskell IO - handle closed
For example, in below:
main = do
x <- getContents
putStrLn $ map id x
x <- getContents --problem line
putStrLn x
the second call x <- getContents will cause the error:
test: <stdin>: hGetContents: illegal operation (handle is closed)
Of course, I can omit the second line to read from getContents.
main = do
x <- getContents
putStrLn $ map id x
putStrLn x
But will this become a performance/memory issue? Will GHC have to keep all of the contents read from stdin in the main memory?
I imagine the first time around when x is consumed, GHC can throw away the portions of x that are already processed. So theoretically, GHC could only use a small amount of constant memory for the processing. But since we are going to use x again (and again), it seems that GHC cannot throw away anything. (Nor can it read again from stdin).
Is my understanding about the memory implications here correct? And if so, is there a fix?
do x <- getContents ; y <- useMyDataSomehow x ; useMoreData y? Anyway your problem might be solved by the pipes/conduit libraries (at the cost of writing your program in the style required by those libraries)do {cs <- getContents; putStrLn cs}uses basically no memory,do {cs <- getContents; putStrLn cs; putStrLn cs}accumulates all ofcsthe first time around. How you 'get around' this will depend on what you are doing. Do you literally want toputStrLntwice? Or e.g record length and print, or what?teecommand or a variant of it.