One of several
A union is a type whose values come in several named shapes, called cases. It is how qdx says “either this or that”, and it is also how it builds a list.
Mira’s score sheet is a list of results. A list is either empty, or one result followed by the rest of the list. Replace scores.qdx with this.
record result { player: bytes, points: int }
union results { no_results(), result_then(first: result, rest: results) }
fn total_for(player: bytes, all: results, sum: int) -> int {
match all {
no_results() => sum,
result_then(first, rest) =>
if bytes_equal(first.player, player) { total_for(player, rest, sum + first.points) }
else { total_for(player, rest, sum) }
}
}
fn main() -> int {
let sheet = result_then(first: result(player: "mira", points: 12),
rest: result_then(first: result(player: "tomas", points: 7),
rest: result_then(first: result(player: "mira", points: 5),
rest: no_results())));
print(concat3("mira has ", int_to_text(total_for("mira", sheet, 0)), "\n"))
}bootstrap/qdx run std/*.qdx scores.qdxmira has 17Declaring a union
union results has two cases. no_results() holds nothing. result_then holds a result and another results, which is what lets the list go on. A case is always written with parentheses, whether it has fields or not.
A case is made the same way a record is: result_then(first: ..., rest: ...).
match
match looks at a union value and runs the arm for its case. Each arm gives the case, new names for its fields in declared order, then => and an expression. Inside the result_then arm, first and rest are the two fields of that case.
Text is compared with bytes_equal, because == works only on numbers and truth values.
Every case, every time
A match must have exactly one arm for each case. If Ines later adds a third case to results, the compiler will stop at every match that has not been updated and name the case it is missing. You cannot forget one.
Both arms must produce the same type, as the two branches of an if do.
The compiler has been agreeing with everything so far. The next chapter shows what it says when it does not.