PeaBox Lab › PeaLang › Learn › Chapter 27 › Lesson 1

Part V — The Modern Experience Layer · Chapter 27 · Lesson 1 of 3

Comprehensions and match expressions

Featherweight syntax changes are the ones people adopt first, and v1.0.0-experience shipped several. This lesson covers the two you will reach for daily: comprehensions and match.

List and dict comprehensions

Comprehensions replace the classic for + push accumulation with a single declarative expression:

let doubled = [x * 2 for x in xs if x > 1]

let squares = {k: v * v for [k, v] in items(d)}

Three details worth internalizing. First, the if clause is a filter, not a guard on execution — items failing it never reach the output. Second, the destructuring for [k, v] form pulls keys and values out of the iterable directly, so unpacking at the boundary of the comprehension costs nothing. Third, dict comprehensions exist alongside list comprehensions, with the same shape.

Membership: in and not in

if user_id in active_user_ids {
  print "returning user"
}

if "error" not in message {
  log.info("clean run")
}

Membership works on lists, dicts (key membership) and strings (substring). Use it instead of .contains(...) == true — it reads better and the stdlib supports it natively.

Power operator: **

let bytes = 2 ** 10        # 1024
let growth = 1.02 ** 12    # compound growth

Pattern matching

match exists as a statement and as an expression. It replaces chains of if/elif where you are inspecting one value against several alternatives:

fn word(n) {
  match n {
    1 => "one",
    2, 3 => "few",
    _ => "many"
  }
}

match event.kind {
  "deploy" => deploy(event.payload),
  "rollback" => rollback(event.payload),
  _ => log.warn("unknown event", kind: event.kind)
}

The _ arm is the catch-all. Arms are literal multi-value patterns — deliberately no guard expressions — which keeps exhaustiveness trivially checkable. If you need richer selection logic, compute a normalized token first and match on it. If the decision table fits in five arms, use match; if the number of arms is unbounded, use a map from key to handler function.

Guided practice

Next →