this may be a stupid question but i couldn’t find answer anywhere. I’m a Haskell newbie and i’m having trouble with I/O.
I have this structure:
data SrcFile = SrcFile (IO Handle) String
srcFileHandle :: SrcFile -> IO Handle
srcFileHandle (SrcFile handle _) = handle
srcFileLine :: SrcFile -> String
srcFileLine (SrcFile _ string) = string
Now the problem is that i have no idea how to assign stdin/stderr/stdout into it, because the stdin etc are Handlers, no IO Handlers. And if i make the structure have Handle attributes insted of IO Handle, then i won’t be able to add any other file handles into it.
Judging from your definition of
SrcFile, it seems as though you may be trying to write a C program in Haskell. Language shapes the way we think, and the good news is Haskell is a much more powerful language!The excellent book Real World Haskell has a section on lazy I/O. Consider an excerpt:
Here’s the radical part.
Further down is a section on
readFileandwriteFilethat shows you how to forget about handles entirely.For example, say you want to grab all the
importlines from a source file:Even though the definition of
mainusesreadFile, the program reads only as much of the named source-file as necessary, not the whole thing! There’s nothing magic going on: note thatcollectImportsusestakeWhileto examine only those lines it needs to rather than, say,filterthat would have to read all lines.When fed its own source, the program outputs
So embrace laziness. Laziness is your friend! Enjoy the rest of the wonderful journey with Haskell.