tobold.org

correct • elegant • free

△ How to do IO in Haskell △

◅ Actions versus computations

The Handle type ▻

Summary of the do expression

We have now met three kinds of statements we can put in a do expression, and there is a fourth: an empty statement. (This will no doubt be a boon to any Haskell user whose keyboard has a stuttering ; key!)

The do expression

When a do expression is evaluated, the statements it contains are evaluated in order. Four types of statements can occur in a do expression:

  1. A bare IO action, like putStrLn "hello". The IO will be performed. If this is the last statement in the do expression, its result becomes the value of the entire expression. Otherwise, any result is discarded.
  2. A name binding, like args <- getArgs. To the right hand side of <- is an IO action to be performed; its result is bound to the name on the left hand side. The name bound is in scope till the end of the do expression.
  3. A let binding, like let acts = map output args. There are no IO actions here: this is exactly like a normal let binding (except there is no in keyword). The names bound are in scope till the end of the do expression. Names bound earlier in the same do expression, whether by let or <-, are of course in scope and may appear on the right hand side of the =.
  4. An empty statement.

The final statement in a do expression must be of type 1, which includes return expressions. This final statement gives its type and value to the entire do expression.

△ How to do IO in Haskell △

◅ Actions versus computations

The Handle type ▻