Haskell IO - hGetContents: illegal operation (handle is closed)
haskell
Solution
I'd suggest you to also investigate an alternative approach. There some inherent problems with `getContents` and similar operations:
- You can have an invalid handle - a handle that is already closed. This is common in most languages, but we can do better. Ideally, we'd like to be sure that once we close a handle, we can't use it further.
- `getContents` is a lazy `IO`, which means (among other problems) that:
- We have little or no control of when (if) the handle is closed.
- While we're processing the string returned by `getContents`, the data are read using lazy `IO` operations. This means that inside pure computations we can get `IO` effects and errors.
A safer alternative is to use another concept, called iteratees, conduits or pipes. The idea is that you describe your components as things that read some input data and/or write output and then combine them together. This allows you to write very robust and elegant code.
Problem
I'm trying to comprehend haskell IO but this feature of stdin ultimately confuses me: When I try to use some function like getContents, for example in: ``` let main = do x<-getContents; putStrLn x ``` I get the following error: ``` hGetContents: illegal operation (handle is closed) ``` How I am supposed to do any IO with this? Is there some fix, or should I look up for another analogical IO function?