Language reference · section 14
14. Typed holes, match, and comprehensions
14.1 Typed holes
Feature: Typed holes
Scenario: An underscore marks a value not yet written
Given the code "x = _"
Then the compiler reports an error "typed hole: write the value here, `_` is a placeholder"
Scenario: A typed hole names the type it needs
Given the code "x: int = _"
Then the compiler reports an error that names the type int
14.2 Match with a subject
Feature: Match with a subject
Scenario: match tests a value against arms
Given a match with an arm for each pattern
When the value matches an arm
Then the arm's expression is the result
Scenario: Patterns are literals, names, wildcards, alternatives, and guards
Given the patterns 1, -1, "a", true, null, n, _, 2 | 3, and n if n > 10
Then each pattern is valid
Scenario: An alternative cannot bind a name
Given the pattern n | 2
Then the compiler reports an error "a binding cannot appear inside an | pattern"
Scenario: A match must handle every value
Given a match with no unguarded wildcard or name arm and no true and false pair
Then the compiler reports an error "this `match` may not handle every value; add a last arm `_ => ...` (or a name) to catch the rest"
Scenario: true and false together handle every boolean
Given a match on a boolean with arms true and false
Then the match is complete
Scenario: A guarded arm does not count as a catch-all
Given a match whose only name arm has an if guard
Then the compiler reports an error that the match may not handle every value
x = match 1:
1 => "a"
_ => "b"
14.3 Match without a subject
Feature: Match without a subject
Scenario: The first true condition gives the value
Given the code:
"""
label = match:
age < 13 => "child"
age < 20 => "teen"
else => "adult"
"""
Then label is the value of the first arm whose condition is true
Scenario: else must be the last arm
Given an else arm before another arm
Then the compiler reports an error "`else =>` must be the last arm"
Scenario: A match without a subject needs an else arm
Given a match: with conditions and no else arm
Then the compiler reports an error "this `match:` needs a last arm `else => ...`, so that every case is handled"
14.4 Comprehensions
Feature: Comprehensions
Scenario: A comprehension maps items
Given the code "[x * x for x in nums]"
Then the result holds the square of each number in nums
Scenario: A when clause filters items
Given the code "[x for x in xs when x > 0]"
Then the result holds only the items greater than 0
Scenario: A comprehension over an object uses key and value
Given the code "[key for key, value of obj when value is 3]"
Then the result holds each key whose value is 3
Scenario: A comprehension must start with a for clause
Given a comprehension whose first clause is when
Then the compiler reports an error "a comprehension must start with a `for` clause"