I’m probably not understanding the IO monad very well.
If I write an application that is expected to run for many months, meanwhile logging its progress, will the IO monad hold all of the log information in RAM until the end?
From the blog on IO Inside, Haskell models the world as
main :: RealWorld -> ((), RealWorld)
so that IO does not occur during the execution of the Haskell part of the code, but only when the application returns from main.
I’m probably completely misinterpreting this. Could someone explain when Haskell actually does IO?
No. You shouldn’t think of “the IO monad” as something that performs actions. It’s just a mathematical way of representing imperative programs. The primitive imperative programs are things like
getChar;>>=is used to glue two programs together into a larger imperative program. The IO monad is the set of all imperative programs.Consider a program such as
This means:
mainis a program that executes the programputStr "Hello, ", and when that is done, executes the programputStrLn "world!". There’s no need for the Haskell interpreter or the compiled program to keep any state in memory except for an instruction pointer, i.e. “where are we, and what do we execute next”.The
RealWorld -> ((), RealWorld)metaphor may have confused you since it seems to imply a transformation of the outside world’s state to a new state that has to be computed in its entirety, after which the world can be updated to reflect the computed state. That is not what happens at all. The Haskell wiki warns about this: