简体   繁体   中英

Haskell IO Monad and memory use

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?

will the IO monad hold all of the log information in RAM until the end?

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

main = putStr "Hello, " >> putStrLn "world!"

This means: main is a program that executes the program putStr "Hello, " , and when that is done, executes the program putStrLn "world!" . There's no need for the Haskell interpreter or the compiled program to keep any state in memory except for an instruction pointer, ie "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:

The following story about IO is incorrect in that it cannot actually explain some important aspects of IO (including interaction and concurrency).

will the IO monad hold all of the log information in RAM until the end?

No. Assuming you are using a sensible logging strategy.

Haskell performs IO when the result is demanded by your program; which for most actions is immediately. (The exception is lazy file input libraries, where files are not necessarily read until the data is used by the program).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM