Part 3 — Types & type classes

3.3 Specifications, overloading, and type classes

Tutorial sequence · Previous: 3.2 Define nonempty subset types

Goal: introduce constants by specification, declare overloaded symbols with type-specific defining equations, define a semigroup type class with generic instances, and prove theorems over sorted type parameters.

Constant specifications and overloading

  • Constant specification (s.specification): declares a constant c satisfying \(\varphi(c)\) without exposing a concrete definition, given a checked witness of the form \(\forall v.\; v = t \to \varphi(v)\). No axiom is added.
  • Overloaded constants (s.overloaded and s.instance_definition): declares a polymorphic symbol (here default) with non-overlapping opaque defining equations at distinct types (T and Prop).

Mojo

specifications.mojo Download
"""Specify constants by a theorem, and define an overloaded constant at two types."""

from judgment import Session, forall, implies


def main() raises:
    var s = Session()
    var T = s.declare_type("T")
    var z = s.symbol("z", T)

    # A witness of the form ∀v. v = t → φ specifies a constant satisfying φ, with no equation.
    var witness = s.theorem("witness")
    var v = witness.bound_var("v", T)
    witness.goal(forall(v, implies(v == z, v == z)))
    var t = witness.tactics()
    _ = witness.by(t.intro_var("a").then(t.intro("h")).then(t.assumption()))
    var spec = s.specification(["c"], witness.finish())
    print(spec.law())

    # An overloaded constant has one opaque equation per instance.
    var header = s.overloaded("default")
    var A = header.type_var("A")
    var default = header.finish(A)
    var at_t = s.instance_definition(default, [T], z)
    print(at_t)
    print(s.instance_definition(default, [s.prop_type()], s.true_()))
    var proof = s.theorem("default_is_z", default.symbol([T]) == z)
    proof.exact(at_t)
    print(proof.finish())

Run from the repository root pixi run core-run docs/examples/library/specifications.mojo

Output

⊢ c = z
⊢ default = z
⊢ default = True
⊢ default = z

Python

specifications.py Download
"""Specify constants by a theorem, and define an overloaded constant at two types."""

from judgment import Session, forall, implies


def main():
    s = Session()
    T = s.declare_type("T")
    z = s.symbol("z", T)

    # A witness of the form ∀v. v = t → φ specifies a constant satisfying φ, with no equation.
    witness = s.theorem("witness")
    v = witness.bound_var("v", T)
    witness.goal(forall(v, implies(v == z, v == z)))
    t = witness.tactics()
    _ = witness.by(t.intro_var("a").then(t.intro("h")).then(t.assumption()))
    spec = s.specification(["c"], witness.finish())
    print(spec.law())

    # An overloaded constant has one opaque equation per instance.
    header = s.overloaded("default")
    A = header.type_var("A")
    default = header.finish(A)
    at_t = s.instance_definition(default, [T], z)
    print(at_t)
    print(s.instance_definition(default, [s.prop_type()], s.true_()))
    proof = s.theorem("default_is_z", default.symbol([T]) == z)
    proof.exact(at_t)
    print(proof.finish())


if __name__ == "__main__":
    main()

Run from the repository root PYTHONPATH=bindings/python:docs/examples/python/library pixi run python docs/examples/python/library/specifications.py

Output

⊢ c = z
⊢ default = z
⊢ default = True
⊢ default = z

Overloaded instance definitions remain opaque to conversion so definitional equality stays uniform; cite the returned equation fact (at_t) explicitly.

Type classes, generic instances, and sorted polymorphism

A type class (s.class_(name)) packages overloaded operations with class axioms. The example builds a semigroup class and proves a generic theorem over it:

  1. Class declaration: semigroup over type parameter a, overloaded binary operation times : a → a → a, and associativity \(\forall x\,y\,z.\; (x \cdot y) \cdot z = x \cdot (y \cdot z)\).
  2. Ground instance: prove semigroup(N) via semigroup.intro() and register it with s.instance(N, semigroup, ...).
  3. Type-constructor instance: define times on list(g) as append, prove semigroup(list(f)) for arbitrary f, and register the generic instance on list. s.of_class(list_(list_(N)), semigroup) then derives membership for nested list types.
  4. Sorted polymorphism: proof.type_var("m", [semigroup]) constrains m to semigroup. Inside the proof, s.of_class(m, semigroup) and semigroup.elim() provide the class associativity law.
  5. Sort-checked instantiation: instantiating reassociate at list(N) succeeds using the checked instance, whereas instantiating at N → N (which has no instance) fails with KERNEL.

Mojo

classes.mojo Download
"""Declare a semigroup class, instances at a type and at list(α) by an instance definition, and use a theorem over a sorted parameter."""

from judgment import Class, Session, arrow, forall


def main() raises:
    var s = Session()
    var N = s.declare_type("N")
    var list_ = s.type_constructor("list", 1)

    # A class: one type variable, an overloaded parameter, and an axiom.
    var builder = s.class_("semigroup")
    var a = builder.type_var("a")
    var times = builder.parameter("times", arrow(a, arrow(a, a)))
    var x = builder.bound_var("x", a)
    var y = builder.bound_var("y", a)
    var z = builder.bound_var("z", a)
    var t = times.symbol([a])
    var semigroup = builder.finish(forall(x, forall(y, forall(z, t(t(x, y), z) == t(x, t(y, z))))))
    print(semigroup.intro())

    # N is a semigroup: prove membership by the class's definition.
    var tn = times.symbol([N])
    var law = s.axiom("times_N_assoc")
    var ns = law.vars("x y z", N)
    var assoc = law.finish(tn(tn(ns[0], ns[1]), ns[2]) == tn(ns[0], tn(ns[1], ns[2])))
    var witness = s.theorem("N_semigroup", semigroup.membership(N))
    var goals = witness.apply(semigroup.intro())
    goals[0].exact(assoc)
    s.instance(N, semigroup, witness.finish())

    # list(g) is a semigroup by a generic instance definition, times[list(g)] = append[g].
    var header = s.symbol("append")
    var b = header.type_var("b")
    var append = header.finish(arrow(list_(b), arrow(list_(b), list_(b))))
    var append_law = s.axiom("append_assoc")
    var e = append_law.type_var("e")
    var xs = append_law.vars("x y z", list_(e))
    var ap = append.symbol([e])
    var append_assoc = append_law.finish(ap(ap(xs[0], xs[1]), xs[2]) == ap(xs[0], ap(xs[1], xs[2])))
    var definition = s.instance_definition(times)
    var g = definition.type_var("g")
    var times_list = definition.finish([list_(g)], append.symbol([g]))
    print(times_list)
    var list_witness = s.theorem("list_semigroup")
    var f = list_witness.type_var("f")
    list_witness.goal(semigroup.membership(list_(f)))
    var list_goals = list_witness.apply(semigroup.intro())
    var x0 = list_goals[0].intro_var("x")
    var y0 = list_goals[0].intro_var("y")
    var z0 = list_goals[0].intro_var("z")
    var unfold = list_goals[0].use(times_list, [f])
    for _ in range(4):
        _ = list_goals[0].focus().at(times.symbol([list_(f)]), 1).rw(unfold)
    list_goals[0].exact(list_goals[0].use(append_assoc, [f], [x0, y0, z0]))
    var sorts = List[List[Class]]()
    sorts.append(List[Class]())
    s.instance(list_, sorts, semigroup, list_witness.finish())
    print(s.of_class(list_(list_(N)), semigroup))

    # A theorem over a sorted parameter, from the class axiom.
    var proof = s.theorem("reassociate")
    var m = proof.type_var("m", [semigroup])
    var p = proof.var("p", m)
    var tm = times.symbol([m])
    proof.goal(tm(tm(p, p), p) == tm(p, tm(p, p)))
    var axiom = proof.use(semigroup.elim(), [m], using=[s.of_class(m, semigroup)])
    proof.exact(proof.use(axiom, terms=[p, p, p]))
    var reassociate = proof.finish()
    print(reassociate)

    # Used at list(N), which the instances make a semigroup; an arrow is refused.
    var ln = list_(N)
    var use = s.theorem("at_lists")
    var q = use.var("q", ln)
    var tq = times.symbol([ln])
    use.goal(tq(tq(q, q), q) == tq(q, tq(q, q)))
    use.exact(use.use(reassociate, [ln], terms=[q]))
    print(use.finish())
    try:
        _ = s.theorem("at_arrows").use(reassociate, [arrow(N, N)])
    except error:
        print(error.kind)

Run from the repository root pixi run core-run docs/examples/library/classes.mojo

Output

[?0] ⊢ (∀x·2:a. ∀x·3:a. ∀x·4:a. times(times(x·2, x·3), x·4) = times(x·2, times(x·3, x·4))) → class.semigroup(TYPE[a])
[g] ⊢ times = append
[assuming 1 axiom] ⊢ class.semigroup(TYPE[list(list(N))])
  axioms: append_assoc
[m] ⊢ ∀p:m. times(times(p, p), p) = times(p, times(p, p))
[assuming 1 axiom] ⊢ ∀q:list(N). times(times(q, q), q) = times(q, times(q, q))
  axioms: append_assoc
KERNEL

Python

classes.py Download
"""Declare a semigroup class, instances at a type and at list(α) by an instance definition, and use a theorem over a sorted parameter."""

from judgment import Class, Session, arrow, forall, JudgmentError


def main():
    s = Session()
    N = s.declare_type("N")
    list_ = s.type_constructor("list", 1)

    # A class: one type variable, an overloaded parameter, and an axiom.
    builder = s.class_("semigroup")
    a = builder.type_var("a")
    times = builder.parameter("times", arrow(a, arrow(a, a)))
    x = builder.bound_var("x", a)
    y = builder.bound_var("y", a)
    z = builder.bound_var("z", a)
    t = times.symbol([a])
    semigroup = builder.finish(forall(x, forall(y, forall(z, t(t(x, y), z) == t(x, t(y, z))))))
    print(semigroup.intro())

    # N is a semigroup: prove membership by the class's definition.
    tn = times.symbol([N])
    law = s.axiom("times_N_assoc")
    ns = law.vars("x y z", N)
    assoc = law.finish(tn(tn(ns[0], ns[1]), ns[2]) == tn(ns[0], tn(ns[1], ns[2])))
    witness = s.theorem("N_semigroup", semigroup.membership(N))
    goals = witness.apply(semigroup.intro())
    goals[0].exact(assoc)
    s.instance(N, semigroup, witness.finish())

    # list(g) is a semigroup by a generic instance definition, times[list(g)] = append[g].
    header = s.symbol("append")
    b = header.type_var("b")
    append = header.finish(arrow(list_(b), arrow(list_(b), list_(b))))
    append_law = s.axiom("append_assoc")
    e = append_law.type_var("e")
    xs = append_law.vars("x y z", list_(e))
    ap = append.symbol([e])
    append_assoc = append_law.finish(ap(ap(xs[0], xs[1]), xs[2]) == ap(xs[0], ap(xs[1], xs[2])))
    definition = s.instance_definition(times)
    g = definition.type_var("g")
    times_list = definition.finish([list_(g)], append.symbol([g]))
    print(times_list)
    list_witness = s.theorem("list_semigroup")
    f = list_witness.type_var("f")
    list_witness.goal(semigroup.membership(list_(f)))
    list_goals = list_witness.apply(semigroup.intro())
    x0 = list_goals[0].intro_var("x")
    y0 = list_goals[0].intro_var("y")
    z0 = list_goals[0].intro_var("z")
    unfold = list_goals[0].use(times_list, [f])
    for _ in range(4):
        _ = list_goals[0].focus().at(times.symbol([list_(f)]), 1).rw(unfold)
    list_goals[0].exact(list_goals[0].use(append_assoc, [f], [x0, y0, z0]))
    sorts = []
    sorts.append([])
    s.instance(list_, sorts, semigroup, list_witness.finish())
    print(s.of_class(list_(list_(N)), semigroup))

    # A theorem over a sorted parameter, from the class axiom.
    proof = s.theorem("reassociate")
    m = proof.type_var("m", [semigroup])
    p = proof.var("p", m)
    tm = times.symbol([m])
    proof.goal(tm(tm(p, p), p) == tm(p, tm(p, p)))
    axiom = proof.use(semigroup.elim(), [m], using=[s.of_class(m, semigroup)])
    proof.exact(proof.use(axiom, terms=[p, p, p]))
    reassociate = proof.finish()
    print(reassociate)

    # Used at list(N), which the instances make a semigroup; an arrow is refused.
    ln = list_(N)
    use = s.theorem("at_lists")
    q = use.var("q", ln)
    tq = times.symbol([ln])
    use.goal(tq(tq(q, q), q) == tq(q, tq(q, q)))
    use.exact(use.use(reassociate, [ln], terms=[q]))
    print(use.finish())
    try:
        _ = s.theorem("at_arrows").use(reassociate, [arrow(N, N)])
    except JudgmentError as error:
        print(error.kind)


if __name__ == "__main__":
    main()

Run from the repository root PYTHONPATH=bindings/python:docs/examples/python/library pixi run python docs/examples/python/library/classes.py

Output

[?0] ⊢ (∀x·2:a. ∀x·3:a. ∀x·4:a. times(times(x·2, x·3), x·4) = times(x·2, times(x·3, x·4))) → class.semigroup(TYPE[a])
[g] ⊢ times = append
[assuming 1 axiom] ⊢ class.semigroup(TYPE[list(list(N))])
  axioms: append_assoc
[m] ⊢ ∀p:m. times(times(p, p), p) = times(p, times(p, p))
[assuming 1 axiom] ⊢ ∀q:list(N). times(times(q, q), q) = times(q, times(q, q))
  axioms: append_assoc
KERNEL

The resulting theorem at_lists records append_assoc in its axiom list: instance derivations are checked kernel derivations rather than an unchecked dispatch table.

Exercise

In classes, how would list_semigroup change if it required the element type f to be a semigroup?

Answer

Declare f = list_witness.type_var("f", [semigroup]) and pass [[semigroup]] as the sorts argument to s.instance(list_, sorts, semigroup, ...). Then list(N) inherits semigroup from N, while list(N → N) is rejected.

Next: 3.4 Class hierarchies, parameterized subsets, and custom ACU.

judgment v1.0.0 for Mojo 1.2 · Apache License 2.0 with LLVM Exceptions · Source on GitHub