HASKELL / CHAPTER 13

Pure computation and IO sequencing

Advanced

Keep transformations pure and sequence external actions at the boundary.

By the end of this chapter

  • Distinguish a value from an IO action
  • Bind an action result inside do
  • Keep reusable transformation logic pure

The idea

Enter with function types and list transformations understood. A pure function computes a result from its inputs without performing external effects. An IO a value describes an action that can produce an a when executed as part of the program’s IO sequence. It is not an a that can be extracted anywhere. The type keeps interactions such as reading input and printing output visible.

Inside do notation, <- binds an action’s result for later actions, while let introduces a pure local definition. Statements in that IO sequence occur in order, even though pure computations remain non-strict. A useful design keeps validation and transformation in pure helpers and lets main handle interaction. This makes the helper easier to reason about independently of terminals, files, and user timing.

Haskell example
double :: Integer -> Integer
double n = n * 2
main :: IO ()
main = do
  let result = double 6
  putStrLn "Result:"
  print result
Result
Result:
12

The helper produces a pure Integer. Main sequences a text output action and then an action that prints the result.

Try it yourself

Write a pure string transformation, then call it after binding a line with <- in main.

Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.

CHECK YOUR UNDERSTANDING

Chapter checkpoint

Inside do, which line reads a line and binds the resulting String?