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. 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 from items(d) directly. 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 {
std.logging.info("clean run")
}
Membership works on lists, dicts (key membership) and strings (substring). Use it instead of .contains(...) == true — the parser handles in and not in directly.
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:
function word(n) {
return match n {
1 => "one"
2, 3 => "few"
_ => "many"
}
}
match event.kind {
"deploy" => deploy(event.payload)
"rollback" => rollback(event.payload)
_ => std.logging.info("unknown event")
}
Arms may be expressions or blocks, and the _ arm is the catch-all. You can add an if guard after the pattern; it is evaluated with the names bound by that pattern:
function label(n) {
return match n {
x if x > 10 => "large"
x if x > 0 => "small"
_ => "other"
}
}
Separate arms with newlines, not commas — a comma belongs to a multi-value pattern such as 2, 3. If no arm matches, a match expression yields null and a match statement does nothing. If the decision table fits in five arms, use match; if the number of arms is unbounded, use a dict from key to handler function.
Guided practice
- Rewrite three
push-based accumulation loops with comprehensions; measure readability, not line count. - Convert an if/elif dispatch on an
actionstring to amatchstatement; verify the catch-all logs unknown actions withstd.logging.info. - Find every
contains(x) == truein your codebase and replace it within.