Types and indexed families¶
An indexed family is a data type whose type carries an index, such as a vector's length, that
each constructor fixes. It is the
inductive family of dependent type theory
(Dybjer, 1994), and in a language without dependent types the
generalized algebraic data type
(GADT) (Xi et al., 2003). A value of Measurement(Observed) and one of Measurement(Missing)
belong to one family, but a well-typed computation cannot use one where the other is expected. The
constructor determines the index, and case analysis refines it inside
each branch.
Kinds and binders¶
A telescope is an ordered list of binders in which later types may mention earlier binders (de Bruijn, 1991). Computations and programs write static binders in square brackets and runtime binders in round brackets. Family declarations additionally use round brackets for their refinable static indices:
| Form | Meaning | Used by |
|---|---|---|
[A : Type] |
static type binder | families, constructors, effects, operations, handlers, computations, programs |
[n : Nat] |
static index binder | families, constructors, effects, operations, handlers, computations, programs |
[Row : FinSet], [f : Mor[A, B]] |
static object or morphism binder | programs |
[E : Effect] |
static binder for an effect interface | declarations, including programs, that abstract over an effect |
[r : Row] |
static binder for a row of record fields or variant alternatives | computations |
(n : Nat) |
family index, refined by case analysis | family declarations and case motives |
(x : T) |
runtime value parameter | computations, programs, and handler clauses |
Static arguments are written in brackets, as in length[Real, S(Z)](xs), and runtime values in
parentheses. An integer literal may fill a Nat static binder, so window[32](xs) is valid when
window binds [n : Nat].
The distinction is semantic: a static argument determines the specialized types, whereas a runtime argument inhabits those types. Whether an argument is written explicitly or inferred is independent of that distinction. The cross-construct parameter reference relates program inputs to constructors, effects, handlers, and family indices.
The built-in value types are Unit, Bool, Int, Real, String, LogWeight,
A[Fin d1, Fin ...], Sampleable[A], and Site[A]. A
product type is written A * B. A tuple value
is written (a, b), and pair[0] and pair[1] project its components.
Record types {l : A, m : B}, variant types <l : A, m>, and function types A -> B !{e} are
described in Records, variants, and function values.
In a program runtime header, (count : Nat) additionally restricts the integer
carrier Int to nonnegative values. The checked input contract preserves this
restriction and execution validates the values given. This use differs from a
static extent [n : Nat] and from the inductive index declaration below.
Index types¶
An index declaration introduces a type of static indices together with all of its constructors:
A constructor may be nullary or recursive. No constructor can be added after the declaration, so
the checker knows every constructor a case must cover. Index values are static terms, not runtime
integers. A Nat literal stands for an index only where a declaration binds a Nat.
Natural-number extent addition¶
The built-in Nat sort admits nat_add(a, b) in index positions. It states
an exact shape relation, rather than adding runtime integer values:
define keep_padded[n : Nat](
x : Real[Fin nat_add(n, 1)],
) : Real[Fin nat_add(1, n)] !{} =
return x
The checker folds closed additions, flattens nested sums, and preserves
nominal variable identities. Thus the two types above agree before n
is specialized. A static n=2 gives a vector of length three.
A program header may use the same shape relation; binding can infer n
from exact tensor-length evidence. Coupled equations such as
n + m = 5 and n + 2m = 8 determine both extents, while one equation
n + m = 5 leaves them underdetermined. Conflicting, negative, and
nonintegral solutions are refused.
A Nat used only in tensor shapes may specialize to zero. It does not
introduce a finite-set object; using it in a categorical finite-object
position retains that position's cardinality requirements. Nat addition
neither creates an axis nor identifies two unrelated axes. There is no
unconstrained Nat subtraction: cancellation may remove a constant already
present in a checked sum, but n - 1 requires evidence absent from a bare
Nat binder.
This uses the existing index-application grammar. In a user-defined index
sort, a constructor named nat_add remains a nominal constructor; it is
not reinterpreted as arithmetic. Program calls retain their current
restriction to names and numeric literals as explicit static actuals;
this addition extends checked index expressions, without changing that
call grammar or converting indices into runtime values.
Family declarations¶
Vec[A](n) is a list of elements of type A whose type also records its length n. Nil has
length Z, and Cons has length one more than its tail, so a computation that requires a nonempty
vector cannot receive Nil. In the terms of inductive families, A is a parameter, fixed across
all constructors, and n is an index, which each constructor sets (Dybjer, 1994). QVR
writes parameters in brackets and indices in parentheses:
index Nat = Z | S(Nat)
family Vec[A : Type](n : Nat) : Type
constructor Nil : Vec[A](Z)
constructor Cons[m : Nat] : A * Vec[A](m) -> Vec[A](S(m))
A case branch cannot change A. It can learn n: matching Nil proves that the index is Z, and
matching Cons[m] proves that it is S(m). A constructor's fields precede ->, and a nullary
constructor has none. The declaration form of a computation
shows how static arguments are received, and the
finite collection operations use the extents they
fix to compute result shapes.
Family names and constructor names live in separate namespaces. A constructor is an ordinary
name: Cons(x, xs) applies it to its fields, and Nil alone is a nullary constructor wherever no
local of that name is in scope. Its static arguments are the family's parameters followed by the
constructor's own telescope, and the elaborator infers them
bidirectionally
(Dunfield and Krishnaswami, 2021). Where a position expects a type, as a return does, a typed
argument, or an annotation, the expected type selects the family and fixes its arguments. Where none
is expected, the fields determine them by unification over the constructor's telescope. A real
vector of three elements is thus built as follows:
index Nat = Z | S(Nat)
family Vec[A : Type](n : Nat) : Type
constructor Nil : Vec[A](Z)
constructor Cons[m : Nat] : A * Vec[A](m) -> Vec[A](S(m))
define triple(a : Real, b : Real, c : Real) : Vec[Real](S(S(S(Z)))) !{} =
return Cons(a, Cons(b, Cons(c, Nil)))
Static arguments may also be written in brackets, Cons[Real, Z](c, Nil), and any value may be
checked against a type with an annotation, (e : T). The two together state every argument the
elaborator would otherwise infer:
index Nat = Z | S(Nat)
family Vec[A : Type](n : Nat) : Type
constructor Nil : Vec[A](Z)
constructor Cons[m : Nat] : A * Vec[A](m) -> Vec[A](S(m))
define single(c : Real) : Real !{} =
let last = (Cons[Real, Z](c, Nil) : Vec[Real](S(Z)))
case last
Cons(x, _) =>
return x
An explicit static argument is checked against what the expected type and the fields imply; a
conflict is refused with both, as in static argument 'A' of constructor 'Cons' is given as Real but
inferred as Int from the expected type Vec[Int, S(Z)]. A static argument nothing determines, as in
let v = Nil, is refused with a request for an annotation.
Two families may declare constructors of one name. Where the expected type is a family, it selects
the constructor; a pattern is always checked against its scrutinee's type, so it is never
ambiguous. Elsewhere the name is refused with every candidate listed, and is resolved by qualifying
it with its family, Tree.Leaf(n), or by an annotation. The elaborator never picks one.
A constructor passed where a collection operation expects a lambda stands for the lambda that
applies it: map(xs, Leaf) applies Leaf to each item, and a constructor applied to some of its
fields, map(xs, Pair(c)), supplies the rest.
Indexed case analysis¶
A case expression is checked against a motive, the result type written as a function of the
scrutinee's indices (McBride, 2002). When the case is checked against a known type, as
the body of a define is, the motive may be left out: it is that type at every index. The same
form, written out, allows a result type that depends on the index:
index Nat = Z | S(Nat)
family Vec[A : Type](n : Nat) : Type
constructor Nil : Vec[A](Z)
constructor Cons[m : Nat] : A * Vec[A](m) -> Vec[A](S(m))
define length[A : Type, n : Nat](xs : Vec[A](n)) : Int !{} =
case xs
Nil =>
return 0
Cons[k](head, tail) =>
let rest <- length[A, k](tail)
return 1 + rest
define copy[A : Type, n : Nat](xs : Vec[A](n)) : Vec[A](n) !{} =
case xs motive (m : Nat) => Vec[A](m)
Nil =>
return Nil
Cons(head, tail) =>
return Cons(head, tail)
Matching Cons[k] shows that the vector has a head and a tail and that its length is one more than
the tail's. The branch binder k is a rigid index, a fresh variable that stands for an unknown
index inside one branch (Peyton Jones et al., 2006). It may fix the type of tail and the static
argument of the recursive call, but it cannot appear in the type of the branch's result. Without
the motive in copy, each branch returns Vec[A](n) read under its own equations: in the Nil
branch n is Z, so Nil, of type Vec[A](Z), is accepted there too. The motive is needed only
where the result type depends on the index in a way those equations do not settle.
A constructor may be omitted only when its result index cannot equal the scrutinee's, which the
checker decides by unification, from the facts that distinct constructors never build equal indices
and that constructors are injective. This rule permits a total head with no Nil branch:
index Nat = Z | S(Nat)
family Vec[A : Type](n : Nat) : Type
constructor Nil : Vec[A](Z)
constructor Cons[m : Nat] : A * Vec[A](m) -> Vec[A](S(m))
define head[A : Type, n : Nat](xs : Vec[A](S(n))) : A !{} =
case xs motive (m : Nat) => A
Cons[k](first, rest) =>
return first
Nil has index Z, which is distinct from S(n), so no value of Vec[A](S(n)) was built by
Nil, and the single branch covers every value of the declared input type.
Patterns¶
A branch of a case is a pattern, an optional guard if e, and a body. The first branch whose
pattern matches and whose guard holds is taken. Patterns are checked against the scrutinee's type,
so a name is read among that type's constructors:
| Pattern | Matches | Binds |
|---|---|---|
_ |
anything | nothing |
x, x : T |
anything, unless the type has a nullary constructor x |
x |
C(p, q), C[k](p, q) |
values built by C whose fields match p and q |
the sub-patterns' names, and k to C's static binder |
3, -1, "name", true, unit |
that literal, for Int, String, Bool, Unit |
nothing |
(p, q) |
tuples whose components match | the components' names |
{l = p, m, ..} |
records whose labels match; m alone binds the label; .. leaves the rest |
the labels' names |
p \| q |
values either alternative matches, tried left to right | the same names, at the same types, in both |
p as x |
values p matches |
x to the whole value, with p's names |
x. p, x y. p |
a constructor field that binds variables, as Lam(x. body) |
the bound variables, and p's names |
Nested, literal, or-, as-, and guarded patterns combine freely:
family Term : Type
constructor Var : Int -> Term
constructor Name : String -> Term
constructor Lam : Term -> Term
constructor App : Term * Term -> Term
define classify(t : Term, k : Int) : Int !{} =
case t
App(Lam(body), Var(n)) if n > k =>
return 1
App(Var(_) | Name(_), arg) as whole =>
return 2
Name("it") =>
return 3
Name(other) =>
return 4
Var(0) =>
return 5
_ =>
return 0
A case on a String or an Int dispatches on literals and, since those types are not finite,
ends in a wildcard or a variable. A tuple pattern matches several values at once:
define both(x : Bool, y : Bool, n : Int) : Int !{} =
case (x, y, n)
(true, true, 0) =>
return 3
(true, _, m) | (_, true, m) =>
return m
_ =>
return 0
A record pattern names labels of a record type, and a binder pattern opens a field that a syntax declares binding, giving its bound variable a name:
syntax Lambda
sorts
Term : object [dim=8]
constructors
Lam : (x : Term).Term -> Term
App : Term, Term -> Term
define weight(r : {scale : Real, active : Bool}) : Real !{} =
case r
{scale, active = true} =>
return scale
{active = false, ..} =>
return 0.0
define bound(t : Lambda.Term) : Lambda.Term !{} =
case t
Lam(x. App(f, a)) =>
return x
other =>
return other
In Lam(x. App(f, a)), x is the variable the Lam binds, Lambda.Term.var(0) in the body's
scope; with several names, as x y. p, the last is the innermost.
A let destructures with any pattern other than a bare name, which is an ordinary local binding,
and the pattern must match every value of the bound type:
pattern P(x, y) = p names a pattern. A use P(a, b) matches p with a and b in place of
x and y, and as an expression builds the value p describes, when p contains no wildcard,
or-, as-, binder, or record pattern (Pickering et al., 2016). Coverage sees the pattern a synonym
stands for, so a synonym loses no exhaustiveness information:
family Term : Type
constructor Var : Int -> Term
constructor Lam : Term -> Term
constructor App : Term * Term -> Term
pattern Redex(body, arg) = App(Lam(body), arg)
define step(t : Term) : Term !{} =
case t
Redex(body, arg) =>
return body
other =>
return other
define example(n : Int) : Term !{} =
let t <- step(Redex(Var(n), Var(0)))
return t
Coverage and redundancy¶
A case must cover its scrutinee's type, and every branch must be reachable. Both are computed with
guard trees, as in Lower Your Guards (Graf et al., 2020): a guard does not count toward coverage, and
a constructor the scrutinee's indices rule out is not demanded. A missing case is refused with a
value no branch matches, and a redundant branch is refused at its line:
case is not exhaustive: no branch matches App(Name(_), _); add a branch for it
the branch at line 12 is redundant: every value it matches is matched by an earlier branch
the branch at line 14 is unreachable: the index equations its constructors establish contradict Vec[Real, S(S(Z))]
A misspelled constructor is a variable, so it matches everything and makes every later branch
redundant, which is how the typo is found. The indices of a value nested inside a match are read
under the equations every enclosing match established: matching Cons[k] on a Vec[A](S(S(Z)))
shows S(S(Z)) = S(k), so the tail Vec[A](k) has length S(Z) and is never Nil:
index Nat = Z | S(Nat)
family Vec[A : Type](n : Nat) : Type
constructor Nil : Vec[A](Z)
constructor Cons[m : Nat] : A * Vec[A](m) -> Vec[A](S(m))
define second(xs : Vec[Real](S(S(Z)))) : Real !{} =
let Cons(_, Cons(b, _)) = xs
return b
A branch whose constructors those equations rule out is refused as unreachable, as a
Cons(_, Cons(_, Cons(_, _))) branch would be here.
Compilation¶
Nested patterns compile to a decision tree over the core's one-level case and if, which tests
each value at most once on every path (Maranget, 2008); literal patterns become equality
tests. A branch body is lowered once: when the tree would reach a body from several places, the
tree returns the selected branch and its bindings as a value of a generated family, and one flat
case on that value runs the body. A default shared by several constructors is compiled once in
the same way, so a match of n columns whose branch i names column i lowers to a tree linear
in n. Bindings that travel this way carry their types with the enclosing index equations solved,
so a body sees the tail of a Cons over Vec[A](S(S(Z))) at Vec[A](S(Z)). When the equations
would constrain a static variable bound outside the match, which a generated value cannot carry,
that part of the tree is lowered without sharing. The reference machine and every target see only
the core's existing terms.
Pure expressions¶
Computation values and program expressions draw on one registry of checked primitives, the
portable set that lowering to the Quivers Indexed Effect Core (QIEC) and program elaboration share. The eager PyTorch compiler accepts
further names of its own, and those names do not become QIEC primitives.
Operators associate to the left within each precedence level:
| Precedence, low to high | Forms |
|---|---|
| Boolean disjunction | || |
| Boolean conjunction | && |
| comparison | ==, !=, <, <=, >, >= |
| additive | +, - |
| multiplicative | *, /, % |
| unary | -, not |
The registry holds typed scalar primitives, reductions, rowwise operations, and the collection forms
of fixed shape map, fold, length, and logsumexp_over.
| Form | Result |
|---|---|
sum, mean, prod, max, min, logsumexp |
collapse the last axis, so shape (n, k) becomes (n,) and a vector becomes a number |
softmax, log_softmax, cumsum, sort, normalize |
act along the last axis and keep the shape |
concat(a, b, ...) |
join tensors along the last axis, whose extents add, with the leading axes equal |
slice(v, start, length) |
keep length entries of the last axis from start, with both bounds integer literals |
select(c, a, b) |
a where the Bool c holds and b elsewhere, entry by entry, with both evaluated |
real(c), int(c) |
read a Bool as one or zero |
matmul(a, b) |
sum the last axis of a against the first axis of a vector or matrix b |
cholesky(a) |
the lower Cholesky factor of each symmetric positive-definite matrix in the last two axes of a real tensor |
layer_norm(v), rms_norm(v) |
normalize each row along the last axis, with an optional real eps |
traverse is computation syntax, not a pure value. The collection forms and their restrictions
are specified in Finite collection expressions, and every primitive is
listed in the
let-expression guide.
Integer division and remainder truncate toward zero on every target. An operation with an Int
and a Real operand converts the Int explicitly where the surrounding form allows it. A
comparison with a negative literal is written x < (-1), because <- is the token of effectful
binding.
Reserved words¶
A let expression reads five words as something other than a name:
| Word | Meaning in an expression |
|---|---|
unit |
the unit value, of type Unit |
true, false |
the Boolean literals |
not |
Boolean negation |
factor |
the start of a factor comprehension |
None of them may name a binder: a sample, observe, or marginalize variable (alone or in a
tuple pattern), a let or score name, a factor binder, a lambda parameter, or a program
parameter. Every later reference to such a binder would read the literal or the keyword, so the
source is refused where the binder is written, as in
reserved word at line 5, col 11: 'unit' names the unit value in expressions, so it cannot name a sample site.
Names that contain or capitalize a reserved word (units, Unit, is_true) are ordinary names,
and so is in, which is a keyword only between a factor's binders and its body.
List literals build tensors over positional axes. [1, 2, 3] is an Int[Fin 3],
[1.0, 2.0, 3.0] a Real[Fin 3], and nested lists add axes. A tensor whose axes are finite types,
such as Real[World], is built by tabulation and read by value
(Tensors indexed by finite types). A distribution family application builds a Sampleable
value, site("x") builds a typed site, and log_prob(distribution, value) returns a LogWeight.
log_mass(distribution) returns its total log mass without introducing
a scoring effect; raw restrictions retain their mass until explicitly
normalized (mass queries).
Common failures¶
- Missing branch. Add a branch for the reported value, unless its result index provably differs from the scrutinee's.
- Redundant branch. Remove it, or correct a misspelled constructor in an earlier branch, which matches everything as a variable.
- Unreachable branch. Remove it: the indices the scrutinee's type and the enclosing matches fix rule out its constructors.
- Ambiguous constructor. Qualify it with its family,
F.c(...), or annotate the value. - Escaped index. Return a type that does not mention a static binder local to a branch, or package the index inside a family whose outer type is fixed.
- Wrong constructor telescope. Give the family's parameters first, then the constructor's own binders.
- Value and static arguments confused. Put types and indices in
[...]and runtime values in(...). - Shadowed primitive type. A telescope binder named
Realis a local type variable, not the primitive type. Rename it unless that abstraction is intended.
Computations covers recursion and binding, and Effects and handlers covers indexed computations that perform requests.
Cited sources¶
Peter Dybjer. Inductive Families. Formal Aspects of Computing, 6(4):440–465, 1994. doi:10.1007/BF01211308.
Hongwei Xi, Chiyan Chen, and Gang Chen. Guarded Recursive Datatype Constructors. In Proceedings of the 30th ACM SIGPLAN-SIGACT Symposium on Principles of Programming Languages (POPL), 224–235. 2003. doi:10.1145/604131.604150.
N. G. de Bruijn. Telescopic Mappings in Typed Lambda Calculus. Information and Computation, 91(2):189–204, 1991. doi:10.1016/0890-5401(91)90066-B.
Jana Dunfield and Neel Krishnaswami. Bidirectional Typing. ACM Computing Surveys, 54(5):98:1–98:38, 2021. doi:10.1145/3450952.
Conor McBride. Elimination with a Motive. In Types for Proofs and Programs (TYPES 2000), Lecture Notes in Computer Science, 197–216. Springer, 2002. doi:10.1007/3-540-45842-5_13.
Simon Peyton Jones, Dimitrios Vytiniotis, Stephanie Weirich, and Geoffrey Washburn. Simple Unification-Based Type Inference for GADTs. In Proceedings of the Eleventh ACM SIGPLAN International Conference on Functional Programming (ICFP), 50–61. 2006. doi:10.1145/1159803.1159811.
Matthew Pickering, Gergő Érdi, Simon Peyton Jones, and Richard A. Eisenberg. Pattern Synonyms. In Proceedings of the 9th International Symposium on Haskell, 80–91. ACM, 2016. doi:10.1145/2976002.2976013.
Sebastian Graf, Simon Peyton Jones, and Ryan G. Scott. Lower Your Guards: A Compositional Pattern-Match Coverage Checker. Proceedings of the ACM on Programming Languages, 4(ICFP):107:1–107:30, 2020. doi:10.1145/3408989.
Luc Maranget. Compiling Pattern Matching to Good Decision Trees. In Proceedings of the 2008 ACM SIGPLAN Workshop on ML, 35–46. ACM, 2008. doi:10.1145/1411304.1411311.