07-control

Level: beginner · Reading time: 3 min · Prerequisite: book/chapters/06-procedures.html · Track: essential · Maturity: reviewed · Last review: 2026-05-09

TL;DR (5 lines)

  • Control flow is about path ownership.
  • A single scenario teaches branches better than isolated snippets.
  • Each branch should change an observable outcome or invariant.
  • Invalid control examples should isolate structural mistakes.
  • Read the path first, the tokens second.

Frequent mistakes

  • Teaching `if`, `for`, and `match` as unrelated pages with no shared scenario.
  • Adding branches that do not change any observable outcome.
  • Using invalid examples that break types instead of control shape.

Prerequisites: book/chapters/06-procedures.html. See also: book/chapters/06-procedures.html, book/chapters/27-grammar.html, book/chapters/31-build-errors.html.

Concrete Problem

Control-flow chapters become repetitive when they explain keywords separately without one scenario showing how branches cooperate.

Red Thread (Single Project)

One scoring flow uses guards, loops, and branching to keep the path explicit from input to output.

For what

This chapter helps the reader decide when to branch, when to loop, and when to stop.

What you are going to do

You will inspect one controlled flow, identify the branch points, then compare it to a malformed control surface.

Coherent example

space demo/control

proc sum_positive(values: list[int]) -> int {
  let acc: int = 0
  for value in values {
    if value < 0 { continue }
    set acc = acc + value
  }
  give acc
}

Global explanation

Control flow must be taught as a route through the program, not as isolated keywords. The reader should see where the path changes, why it changes, and how the result remains understandable.

Invalid case

proc bad_control(x: int) -> int {
  if x { give 0 }
  give x
}

This invalid case is intentionally small. It exists to isolate the contract failure that the chapter is trying to teach.

Common pitfalls

  • Teaching `if`, `for`, and `match` as unrelated pages with no shared scenario.
  • Adding branches that do not change any observable outcome.
  • Using invalid examples that break types instead of control shape.

Short exercise

Add one fallback branch to the example and explain what new path it creates.

Summary in 5 points

  1. Control flow is about path ownership.
  2. A single scenario teaches branches better than isolated snippets.
  3. Each branch should change an observable outcome or invariant.
  4. Invalid control examples should isolate structural mistakes.
  5. Read the path first, the tokens second.

Mini quiz

  1. What contract is the coherent example trying to make explicit?
  2. Why does the invalid example fail?
  3. What boundary should remain visible if you extend the example?

See also

Next best action

Extend the coherent example by one small, justified step and keep the same contract visible from input to output.