Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell IO Monad and memory use

Tags:

io

haskell

monads

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?

like image 836
Ralph Avatar asked Jun 04 '12 11:06

Ralph


1 Answers

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, 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:

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

like image 168
Fred Foo Avatar answered Oct 13 '22 00:10

Fred Foo