Milestone M7
Algebraic Data Types and Pattern Matching
Part VIII gave Bridger a way to declare data and a way to take it apart. Sum and product
types added type declarations and constructors. Pattern
matching added match, guards, and ?, and Exhaustiveness
checking added the premise of T-Match that requires the arms to cover
their scrutinee’s type. This milestone builds all of it, and the prelude’s Option, Result, and
Ordering constructors come to life with it. Every M1–M6 test must still pass.
The work is in three files you have already edited: the evaluator in src/interp/eval.rs, the
checker in src/types/check.rs, and the rule checks in src/relations/check.rs.
To-dos
grep -rn 'todo_m7!' src lists the holes:
// src/interp/eval.rs
Expr::Ctor(..) => todo_m7!("E-Ctor"),
Expr::Match(..) => todo_m7!("E-Match"),
Expr::Try(..) => todo_m7!("E-Try (`?`: match + return)"),
// src/types/check.rs
Expr::Ctor(..) => todo_m7!("T-Con"),
Expr::Match(..) => todo_m7!("T-Match (patterns, then exhaustiveness)"),
Expr::Try(..) => todo_m7!("T-Try"),
// src/relations/check.rs
pub fn check_guards(program: &Program) -> Result<(), RuleError>
Pasting the declarations from Exhaustiveness below adds their todo_m7! holes
to src/types/check.rs.
Two changes have no todo_m7! marker of their own:
- The checker’s
Lambdaarm reports a?that a lambda’s body cannot carry, as described below. - Your purity judgment from M6 needs to handle constructor applications,
match, and?, which no M6 program could reach. Appendix D gives the rules: a constructor application is pure when its arguments are, and amatchwhen its scrutinee, guards, and bodies are.?is pure at this milestone, because it is amatchand areturn, and noimpl Fromexists yet.
How to know it works suggests an order for the work.
Milestone specification
The forms, the rules that give them meaning, and the cases in which evaluation is stuck or the checker rejects them:
| Form | Rules | Stuck when | Rejected when |
|---|---|---|---|
C(e1, …, en) |
E-Con, T-Con |
C is not a declared name (UnboundVariable); C names a
type or struct and has arguments (NotAFunction); the count differs from the
declaration (ArityMismatch) |
C is unknown (UnknownConstructor) or names a type, struct, or trait
(NotAConstructor); the count differs (ArityMismatch); an argument has
the wrong type |
match e { p [if g] => b, … } |
E-Match, T-Match |
a guard is not a Bool (TypeError, at the guard); no arm applies
(NonExhaustiveMatch, at the match) |
a pattern does not fit the scrutinee's type; a guard is not a Bool; bodies
disagree (Mismatch); the unguarded arms do not cover the type
(NonExhaustiveMatch, at the match); a guard is not pure
(ImpureGuard, HigherOrder) |
e? |
desugars to match and return |
e is not an Ok, Err, Some, or
None (NonExhaustiveMatch, at the ?) |
e is not an Option or Result
(TryOnNonCarrier); the enclosing function cannot carry the failure
(TryInNonCarrierFunction, TryInLambda); the two error types differ
(Mismatch) |
The patterns, each of which is an arm of your matcher and of check_pattern:
| Pattern | Matches | Rejected when |
|---|---|---|
_ | anything | never |
x | anything, binding x |
x is already bound in this pattern (NonLinearPattern) |
| a literal | an equal value | its type is not the scrutinee's |
C(p, …) | that constructor, with matching arguments | as for a C(e, …) expression; its type is not the scrutinee's |
(p, q, …) | a tuple of that width, with matching components | the scrutinee is not such a tuple |
[p, …], [p, …, ...t] |
exactly that many elements, or at least that many with t as the rest |
the scrutinee is not a list; t is already bound |
h :: t | a non-empty list | the scrutinee is not a list |
S { f: p, … } |
that struct, with the named fields matching | S is unknown (UnknownType) or names something other than a struct
(NotAStruct); a field is repeated (DuplicateField) or undeclared
(NoSuchField); its type is not the scrutinee's |
p | q | either side, trying p first |
the sides differ in their variables or their types (OrPatternBindings) |
match(p, v) and E-Match are in
Appendix D, T-Con and T-Match
under its typing rules, and the static errors are
catalogued by name. Struct values do
not exist until M8, but struct patterns are part of the matcher, the checker, and exhaustiveness
now.
Implementing Milestone M7
The provided runtime
A constructor value is Value::Ctor(name, args), with its arguments in an Rc<[Value]>. A list is
Value::List(List), whose uncons returns the head and a reference to the tail. Keep the sharing:
a :: or ...rest pattern binds the tail it was given, and cloning a List is cheap, whereas
rebuilding one would make a recursion over a list quadratic. Pattern::binders in ast.rs lists
the names a pattern binds. Finding a constructor’s declaration is a walk over Decl::Type entries
in the program’s decls, whose variants carry their names and field types.
A struct declaration is Decl::Struct(generics, fields), and a struct value is
Value::Struct(name, fields), with its fields as name and value pairs in an Rc<[(Name, Value)]>.
No program can build one yet, since Expr::Struct is a todo_m8!, so at this milestone only the
checker and exhaustiveness halves of a struct pattern can run against a real struct. Against any
other value, the matcher’s struct arm reports that the value does not fit.
The evaluator’s arms
Ctordecides what its name means before it runs the arguments. With no arguments, a name that isInt,Bool,String, or a declared type or struct is the type itself, aValue::Type, which M8’s associated calls use as a receiver. Any other declared name that is not a constructor isNotAFunction, withfoundthe named typetype N. A name that is not declared isUnboundVariable. It then evaluates the arguments left to right and checks the argument count afterward, reportingArityMismatchat the whole expression if the count differs from the declaration.- The matcher is one recursive function following . A value that does not
fit is an ordinary result that sends the evaluator to the next arm, and it never becomes a
RuntimeError. Its literal arm compares the value it is given with the value the literal denotes. Matchevaluates the scrutinee once, then tries the arms in order. Each arm’s bindings extend the environment at thematch, for that arm’s guard and body. A guard that is not aBoolisTypeError { expected: Bool, found, span }at the guard, withfoundfromtype_of. After the last arm, the result isNonExhaustiveMatchat thematch.Tryreturns the argument of anOkorSome. On aNoneor anErr, it raisesControl::Returnholding that same value, the signal yourreturnarm uses, so the enclosing function’s call handles it. Any other value isNonExhaustiveMatchat the?.
The checker’s arms
Each arm ends as M5’s did, with the final unification against the expected type and the record.
Ctorlooks the name up as the table says, with the wrong-arity report made before any argument is checked. It maps the declaration’s type parameters to fresh inference variables, records any declared bound withrequire_traitas yourVararm does, and builds the constructed type. If the expected type has the same head, unify with it now, so that an argument such as an unannotated lambda is checked against a known type. Each argument is then checked against its field’s type with the map applied.check_patterntakes a pattern, the scrutinee’s type, and a context to extend. It also needs to know which variables this pattern has bound so far, to raiseNonLinearPatternat the second occurrence and to compare the sides of an|. A...restbinder goes through the same path as a variable, at the type of the list. An|checks each side on its own context. Both must bind the same names, and their types must unify, or the result isOrPatternBindingsat the whole pattern. A struct pattern looks its name up first. It then rejects a repeated field, and instantiates the declaration’s type parameters as a constructor pattern does before unifying with the scrutinee’s type. Each named field’s pattern is checked against that field’s type with the map applied, and an undeclared field isNoSuchFieldat the field’s pattern. Every mismatch is reported at the pattern’s own span. In aMismatch, the scrutinee’s type isexpectedand the pattern’s isfound.Matchchecks the scrutinee with no expected type. If the scrutinee diverges, calldead_afterwith the scrutinee’s span and the span of thematch. The result type is the expected type if there is one, or a fresh variable. Each arm checks, on its own copy of the context, its pattern, its guard againstBool, and its body against the result type. Exhaustiveness comes after every arm, so a disagreeing arm is reported ahead of a gap: whenis_exhaustiveis false, the result isNonExhaustiveMatchat thematch. If there is at least one arm and every body diverges, callrecord_divergingon thematch.
Try
? checks its operand with no expected type. An operand that diverges calls dead_after and the
form takes a fresh variable. After resolving the operand’s type:
- A
Result<T, E>requires the context’s return type,ctx.ret(), to unify with aResultof some freshT'andE'. No return type at all isReturnOutsideFunction, and a return type that will not unify isTryInNonCarrierFunction { ret, span }, orTryInLambda { found: ret, span }whenctx.in_lambda()holds. ThenEmust unify withE', and if it does not, the result isMismatch { expected: E', found: E, span }. The form’s type isT. - An
Option<T>is the same withOptionin place ofResult, and has no error type to compare. - An unsolved inference variable is
Ambiguous, unlessin_dead_codeholds for the form, where it takes a fresh variable. Any other type isTryOnNonCarrier { found, span }.
If the return type is an inference variable when ? constrains it, call note_try_pinned
with its id. The Lambda arm reads that back through try_pinned. When a lambda has no written
result type, a ? inside it pinned the inference variable for that result type, and checking the
lambda’s body fails with a Mismatch whose expected type is that pinned result type, replace the
error with TryInLambda using the same found type and span. Any other error from the body stays
as it is.
Exhaustiveness
Exhaustiveness checking defines the check, and its summary of the parts divides it into a reduction of patterns to wildcards, constructors, and alternatives; a function from a type to its signature; and with its helpers and . The module below provides , , and . You write the reduction and the signature, and the method that joins them.
Paste the module at the end of src/types/check.rs, unchanged, and add
use exhaustive::{Con, Pat, Signature}; to the file’s imports. Its public function is
covers(rows, ty, signature), which holds when no value of ty escapes every row, with one Pat
per row. It asks signature for the constructors of each column’s type as replaces a column by
a constructor’s arguments, so the column types and the splitting of | alternatives happen inside
it. Within the module, useful is , specialize is , and default_rows is . Nothing
reaches the module until your code calls covers, which is why it allows dead_code.
/// Provided helpers (Milestone M7): the usefulness test behind
/// exhaustiveness checking. Paste this module at the end of the file,
/// unchanged. Until `is_exhaustive` calls `covers`, nothing reaches this
/// module, so `dead_code` is allowed here.
#[allow(dead_code)]
pub mod exhaustive {
use crate::ast::{Name, Ty};
use std::collections::HashSet;
/// A pattern as the usefulness test sees it: a wildcard, a constructor
/// applied to sub-patterns, or two alternatives. A variable is a
/// wildcard here, since it matches anything.
#[derive(Clone, Debug)]
pub enum Pat {
Wild,
Con(Con, Vec<Pat>),
Or(Box<Pat>, Box<Pat>),
}
/// The constructor at the head of a pattern. Literals are constructors
/// with no arguments; a tuple of width n is one constructor of arity n;
/// a list is `Nil` or `Cons(head, tail)`; a struct is one constructor
/// whose arguments are its fields in declaration order.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub enum Con {
Int(i64),
Bool(bool),
Str(String),
Unit,
Tuple(usize),
Nil,
Cons,
Ctor(Name),
Struct(Name),
}
/// A type's constructors, each with its argument types.
pub type Signature = Vec<(Con, Vec<Ty>)>;
/// The function `covers` asks for a type's signature: `None` for a type
/// that only a wildcard covers (`Int`, `String`, a function, ...).
pub type SignatureOf<'a> = dyn Fn(&Ty) -> Option<Signature> + 'a;
/// One row of the pattern matrix: a pattern per column.
type Row = Vec<Pat>;
/// Whether the rows cover every value of `ty`: no value of that type
/// escapes all of them.
pub fn covers(rows: &[Pat], ty: &Ty, signature: &SignatureOf<'_>) -> bool {
let matrix: Vec<Row> = rows.iter().map(|p| vec![p.clone()]).collect();
!useful(&matrix, &[Pat::Wild], std::slice::from_ref(ty), signature)
}
/// Whether some value (of `tys`, one type per column) matches `q` and
/// no row of `rows`.
fn useful(rows: &[Row], q: &[Pat], tys: &[Ty], sig: &SignatureOf<'_>) -> bool {
let Some((head, q_rest)) = q.split_first() else {
return rows.is_empty();
};
let (ty, tys_rest) = (&tys[0], &tys[1..]);
// Continue with `pats` in place of the first column.
let go = |rows2: &[Row], pats: Vec<Pat>, arg_tys: Vec<Ty>| {
let mut q2 = pats;
q2.extend_from_slice(q_rest);
let mut tys2 = arg_tys;
tys2.extend_from_slice(tys_rest);
useful(rows2, &q2, &tys2, sig)
};
match head {
Pat::Or(a, b) => {
go(rows, vec![(**a).clone()], vec![ty.clone()])
|| go(rows, vec![(**b).clone()], vec![ty.clone()])
}
Pat::Con(c, args) => {
let arg_tys = arg_types(sig(ty), c, args.len());
go(&specialize(rows, c, args.len()), args.clone(), arg_tys)
}
Pat::Wild => {
let heads = head_constructors(rows);
let complete = sig(ty).filter(|cons| is_complete(cons, &heads));
match complete {
Some(cons) => cons.into_iter().any(|(c, arg_tys)| {
let rows2 = specialize(rows, &c, arg_tys.len());
go(&rows2, vec![Pat::Wild; arg_tys.len()], arg_tys)
}),
None => useful(&default_rows(rows), q_rest, tys_rest, sig),
}
}
}
}
/// Constructor `c`'s argument types, or `n` placeholders when the type
/// has no signature (a literal of `Int` or `String`).
fn arg_types(sig: Option<Signature>, c: &Con, n: usize) -> Vec<Ty> {
let found = sig.and_then(|s| s.into_iter().find(|(k, _)| k == c));
match found {
Some((_, tys)) => tys,
None => vec![Ty::meta(u32::MAX); n],
}
}
/// Whether every constructor of a (non-empty) signature heads some row.
fn is_complete(sig: &Signature, heads: &HashSet<Con>) -> bool {
!sig.is_empty() && sig.iter().all(|(c, _)| heads.contains(c))
}
/// Every constructor at the head of some row, alternatives flattened.
fn head_constructors(rows: &[Row]) -> HashSet<Con> {
fn heads(p: &Pat, out: &mut HashSet<Con>) {
match p {
Pat::Wild => {}
Pat::Con(c, _) => {
out.insert(c.clone());
}
Pat::Or(a, b) => {
heads(a, out);
heads(b, out);
}
}
}
let mut out = HashSet::new();
for p in rows.iter().filter_map(|row| row.first()) {
heads(p, &mut out);
}
out
}
/// The rows specialized to constructor `c` of arity `n`: a row headed
/// by `c` gives its arguments then its other columns, a row headed by a
/// wildcard gives `n` wildcards then its other columns, and a row headed
/// by another constructor is dropped.
fn specialize(rows: &[Row], c: &Con, n: usize) -> Vec<Row> {
let mut out = Vec::new();
for row in rows {
let Some((head, rest)) = row.split_first() else {
continue;
};
match head {
Pat::Con(k, args) if k == c => {
out.push([args.as_slice(), rest].concat());
}
Pat::Con(..) => {}
Pat::Wild => {
let wilds = vec![Pat::Wild; n];
out.push([wilds.as_slice(), rest].concat());
}
Pat::Or(a, b) => {
for alt in [a, b] {
let r = [std::slice::from_ref(&**alt), rest].concat();
out.extend(specialize(&[r], c, n));
}
}
}
}
out
}
/// The rows headed by a wildcard, without that column.
fn default_rows(rows: &[Row]) -> Vec<Row> {
let mut out = Vec::new();
for row in rows {
let Some((head, rest)) = row.split_first() else {
continue;
};
match head {
Pat::Wild => out.push(rest.to_vec()),
Pat::Con(..) => {}
Pat::Or(a, b) => {
for alt in [a, b] {
let r = [std::slice::from_ref(&**alt), rest].concat();
out.extend(default_rows(&[r]));
}
}
}
}
out
}
}
Then paste these declarations into the impl Checker block, beside your other methods. Their
comments state what a test will hold each one to:
/// Exhaustiveness (T-Match's last premise): whether the unguarded arms
/// cover every value of `scrut_ty`. A guarded arm contributes no row,
/// since its guard may fail. Builds one `Pat` per unguarded arm with
/// `normalize` and asks `exhaustive::covers`, passing `signature`.
fn is_exhaustive(&self, arms: &[Arm], scrut_ty: &Ty) -> bool {
let _ = (arms, scrut_ty);
todo_m7!("is_exhaustive: unguarded arms -> rows -> exhaustive::covers")
}
/// A pattern as the usefulness test sees it. A variable is `Pat::Wild`.
/// A literal is a constructor with no arguments. A tuple pattern is
/// `Con::Tuple(width)` over its parts. A list is built from `Con::Nil`
/// and `Con::Cons(head, tail)`: `[p, q]` is `Cons(p, Cons(q, Nil))`, and
/// `[p, ...rest]` is `Cons(p, Wild)`. A struct pattern is
/// `Con::Struct(name)` over every declared field in declaration order,
/// an unmentioned field as `Pat::Wild`.
fn normalize(&self, p: &Pattern) -> Pat {
let _ = p;
todo_m7!("normalize: Pattern -> exhaustive::Pat")
}
/// The constructors of `ty`, each with its argument types, or `None`
/// for a type only a wildcard covers: `Int`, `String`, a function, a
/// reference, a type parameter, an unsolved variable. Resolve `ty`
/// first. A generic type's constructors take its type arguments: the
/// signature of `Option<Bool>` is `Some` with `[Bool]`, then `None`.
fn signature(&self, ty: &Ty) -> Option<Signature> {
let _ = ty;
todo_m7!("signature: a type's constructors and their argument types")
}
covers takes the signature function as a closure over the checker, written
&|t| self.signature(t). A test will also hold you to these points:
Option<Bool>is completed bySome(true),Some(false), andNoneonly ifsignatureapplies the type’s arguments to its constructors’ field types.IntandStringhave literals but no signature, so amatchover either needs an arm that matches anything.
A struct has a single constructor, so one struct pattern covers its type when the patterns for its fields cover theirs. The M8 tests hold you to this, once struct values exist.
Guards
check_guards visits every fn body, global initializer, impl method, and rule conjunct. It
reports the first offender in source order, sorted by source and position, since the order of
decls is not the order of the file. Within a body, a match’s own guards come before those nested
further in. The walker from M6’s helper module already yields guards.
Each guard is judged by your M6 purity judgment, with its pattern variables as locals, and with one
difference from a rule filter: recursion is allowed, because a guard runs once per arm and need not
contribute to a fixpoint. A guard that reaches a function with a function-typed parameter is
HigherOrder, as a filter is. An impure guard is ImpureGuard { span, witness }, at the guard,
with the chain of calls to the effect. A call through a local closure g has the witness ["g"].
Running a program
cargo run --features m7 runs the static checks and then main. calc.brg uses constructors,
match, and ? together:
$ cat calc.brg
type Calc = Num(Int) | Add(Calc, Calc) | Div(Calc, Calc);
fn result(e: Calc) -> Result<Int, String> = match e {
Num(n) => Ok(n),
Add(l, r) => Ok(result(l)? + result(r)?),
Div(l, r) => {
let d = result(r)?;
if d == 0 { Err("divide by zero") } else { Ok(result(l)? / d) }
},
};
fn main() {
println(result(Add(Num(1), Div(Num(8), Num(2)))));
println(result(Div(Num(1), Add(Num(0), Num(0)))));
}
$ cargo run -q --features m7 -- calc.brg
Ok(5)
Err("divide by zero")
gap.brg has a function over Calc that forgets Div. main never builds one, but the program
never starts, and its println("start") prints nothing:
$ cat gap.brg
type Calc = Num(Int) | Add(Calc, Calc) | Div(Calc, Calc);
fn size(e: Calc) -> Int = match e {
Num(_) => 1,
Add(l, r) => 1 + size(l) + size(r),
};
fn main() {
println("start");
println(size(Num(1)));
}
$ cargo run -q --features m7 -- gap.brg
× match is not exhaustive
╭─[gap.brg:3:27]
2 │
3 │ fn size(e: Calc) -> Int = match e {
· ────┬────
· ╰── here
4 │ Num(_) => 1,
╰────
The exit status is 1. The checker runs first, so no program containing a match runs under
--features m7 until the checker’s arms are written: the first todo_m7! it meets stops the run.
Worked examples
Each expression below has the value at its right:
match [4, 5, 6] { [a, b, ...t] => (b, t), _ => (0, []) } (5, [6])
match [1, 2] { x :: y :: [] => x + y, _ => 0 } 3
match () { () => "unit" } "unit"
match false { true => 1, false => 2 } 2
match (1, Some("x")) { "x"
(_, None) => "a",
(n, Some(s)) if n > 1 => "b",
(_, Some(s)) => s,
}
match Err("no") { Ok(n) if n > 0 => n, Ok(_) | Err(_) => 0 } 0
The checker rejects each of these:
match (Some(1), true) { (None, _) => 0, (_, false) => 1 }
NonExhaustiveMatch, at the match
match 1 { 0 => "z", n => n } Mismatch (expected String, found Int), at n
match (1, 2) { (a, a) => a, _ => 0 }
NonLinearPattern (a), at the second a
match Some(1) { Some(a) | None => 0 }
OrPatternBindings (a), at the whole pattern
match Some(1) { Ok(a) => a, _ => 0 }
Mismatch (expected Option<Int>,
found Result<_, _>), at Ok(a)
match Some(1) { Some(a, b) => 0, _ => 1 }
ArityMismatch (Some: 1, given 2)
match 1 { Foo(y) => 0, _ => 1 } UnknownConstructor (Foo)
match 1 { Option(y) => 0, _ => 1 } NotAConstructor (Option)
match 1 { k if k => 0, _ => 1 } Mismatch (expected Bool, found Int), at k
1? TryOnNonCarrier (Int)
The guard checks reject the first two of these. The third is accepted, because a guard may reach a recursive function:
fn ping(k: Int) -> Bool { println(k); true }
match 1 { k if ping(k) => 0, _ => 1 } ImpureGuard, witness [ping, println]
match 1 { k if { println(k); true } => 0, _ => 1 }
ImpureGuard, witness [println]
fn up(k: Int) -> Bool = up(k + 1);
match 1 { k if false and up(k) => 0, _ => 1 } accepted; the value is 1
How to know it works
cargo m7 runs the provided milestone M7 tests and, with them, every earlier milestone’s. Some run
a whole program with run_program, which skips the static checks, so the evaluator meets programs
the checker would have refused. Some call Checker::check_program on a loaded program, and some
call check_guards alone. A rejection is tested by its error variant and, where it matters, by its
payload, and the text of a message is never tested.
Write the matcher and the evaluator’s arms first, since the whole-program tests reach them without
the checker. Then write check_pattern and the checker’s arms with an is_exhaustive that returns
true, and fill in the check once the rest passes. check_guards can come at any point
after that.
Design problems
Write a compiler from Arith to a stack machine, with instructions Push(Int), AddTop, and MulTop, and a function run that executes a list of instructions on a stack and returns Option<Int>. Argue that it agrees with value.
type Arith = Num(Int) | Add(Arith, Arith) | Mul(Arith, Arith);
type Instr = Push(Int) | AddTop | MulTop;
fn compile(e: Arith) -> [Instr] = match e {
Num(n) => [Push(n)],
Add(l, r) => compile(l) ++ compile(r) ++ [AddTop],
Mul(l, r) => compile(l) ++ compile(r) ++ [MulTop],
};
fn run(code: [Instr], stack: [Int]) -> Option<Int> = match (code, stack) {
([], [top]) => Some(top),
([], _) => None,
(Push(n) :: rest, s) => run(rest, n :: s),
(AddTop :: rest, b :: a :: s) => run(rest, (a + b) :: s),
(MulTop :: rest, b :: a :: s) => run(rest, (a * b) :: s),
(_ :: _, _) => None,
};
run(compile(Add(Num(3), Mul(Num(4), Num(2)))), []) is Some(11). Without the last arm the checker
rejects run, because the value (AddTop :: [], []) fits no arm: an instruction that needs two
operands on a stack that has too few.
The claim to prove is stronger than the one asked for, since compile(l) runs with instructions
after it and values under it. For every e, k, and s, run(compile(e) ++ k, s) equals
run(k, value(e) :: s). The proof is by induction on e, with one case per constructor. Num(n)
is one Push step. For Add(l, r), the induction hypothesis applied to l and then r leaves
value(r) :: value(l) :: s, and AddTop replaces those with their sum. Taking k as [] and s
as [] gives the result. The recursion in compile, the cases of the proof, and the arms of the
match all follow the alternatives of the declaration.
Given type Nat = Zero | Succ(Nat); and relation p : (Nat);, the rule rule p(Succ(x)) :- p(x); does not parse, because a rule's arguments are variables and literals. Suppose it did. What would happen to the fixpoint, and is a constructor in a rule body any safer?
With add p(Zero), the rule derives Succ(Zero), then Succ(Succ(Zero)), and so on with no end.
Evaluating relations guaranteed termination because every value in a
derived fact already occurs in some fact, which leaves a finite set of possible facts. A constructor
in a head builds values that occur nowhere, so that set is infinite and the rounds never finish.
This is the difference between Datalog and Prolog, whose terms may be compound and whose programs
need not terminate.
A constructor pattern in a body position, as in rule q(x) :- p(Succ(x));, only takes existing
values apart. Every x it binds is a part of a value already present, and the parts of a finite set
of finite values are finite, so termination would survive. Matching would have to look inside
values, which makes unify a little more than the comparison of variables and constants that it is
now. Facts can already hold constructor values today, and a rule filter can open them with a
match.
Bridger accepts a match with an arm that can never run. Using usefulness, say how to detect such an arm, trace it on arms Some(x), None, Some(1), _, and say how guards change the answer.
Arm can run exactly when holds, where has a row for each
earlier arm. For Some(1), the earlier rows are Some(x) and None. The head of is the
constructor Some, so specializes: the row None drops, the row Some(x) becomes a wildcard,
and becomes 1. Specializing again by the literal 1, the wildcard row leaves a row with no
columns and has none either. A row remains, so is false and the arm can never run. For _,
the rows Some(x), None, and Some(1) make the heads complete. Specializing by Some leaves
the rows and 1, whose heads are incomplete, and keeps the wildcard row, so is
false. Specializing by None leaves a row with no columns, also false. _ can never run
either.
A guarded earlier arm contributes no row, since its guard may fail. A guarded arm is still tested by its own pattern: if the pattern is useless, the guard cannot help it. An unreachable arm is usually a mistake, such as a general arm written above a specific one, and many compilers warn about it. Bridger could add such a warning and still accept the same programs.
The checker reports only that a match is not exhaustive. Change U so it returns an example of a missing value, and give the example it produces for zip_with from the chapter.
Have return an optional vector of patterns, one per column, where it now returns true or false.
With no columns, a useful vector is the empty vector. A constructor head of or a complete
signature recurses: if the recursion on returns , the result is
. In the default case, if the recursion on returns ,
the first column needs a value no row’s head covers. If no row has a head at all, it is . If
some do and the type has a signature, it is any constructor missing from the heads, with wildcards
for its arguments. For an Int, it is again, or any literal the rows do not mention.
For zip_with, the tuple step wraps the result. In the :: branch, the first column gives
_ :: _, the wildcards give , and the last column is the default case with :: present and
[] missing, so the witness is (_ :: _, []): a non-empty first list and an empty second one. A
message built from this tells the programmer which case to add, with the wildcards standing for
parts that do not matter.