Optional packages

judgment_nat reference

The public API of the optional natural-number package: every name its __init__.mojo exports, rendered from the sources' docstrings. The contract is on the natural numbers implementation page and the mathematics on the theory page. Build the package with pixi run build-nat.

Example

primrec.mojo Download
"""Build the natural numbers by definitions and define a function by primitive recursion."""
from judgment_shell import Session, arrow, exists, forall, implies, lambda_
from judgment_nat import NatName, build_arithmetic, build_nat, define_primrec, recognize
from termbank import Budget


def classical_profile(s: Session) raises:
    """Declare choice, function extensionality, and infinity as axioms."""
    var a = s.type_var("demo.a")
    var b = s.type_var("demo.b")
    var prop = s.prop_type()
    _ = s.symbol("demo.epsilon", arrow(arrow(a, prop), a))
    var p = s.bound_var("P", arrow(a, prop))
    var x = s.bound_var("x", a)
    var eps = s.import_symbol("demo.epsilon", [a])
    _ = s.axiom("demo.choice", forall(p, forall(x, implies(p(x), p(eps(p))))))
    var f = s.bound_var("f", arrow(a, b))
    var g = s.bound_var("g", arrow(a, b))
    var y = s.bound_var("y", a)
    _ = s.axiom("demo.funext", forall(f, forall(g, implies(forall(y, f(y) == g(y)), f == g))))
    var ind = s.declare_type("demo.ind")
    var sv = s.bound_var("s", arrow(ind, ind))
    var z = s.bound_var("z", ind)
    var u = s.bound_var("u", ind)
    var w = s.bound_var("w", ind)
    var injective = forall(u, forall(w, implies(sv(u) == sv(w), u == w)))
    var outside = forall(u, ~(sv(u) == z))
    _ = s.axiom("demo.infinity", exists(sv, exists(z, injective & outside)))


def main() raises:
    var s = Session(work=100000000)
    var budget = Budget(UInt64.MAX)
    classical_profile(s)
    var inputs = recognize(s, budget)
    var nat = build_nat(s, inputs, budget)
    var arithmetic = build_arithmetic(s, nat, budget)
    print("Rows:", len(nat.rows), "then", len(arithmetic.names), "arithmetic declarations")
    print("Induction:", nat.get(NatName.INDUCT).name)
    # double := rec zero (λn r. suc (suc r)).
    var n_type = s.import_type(nat.get(NatName.NAT).name)
    var n = s.bound_var("n", n_type)
    var r = s.bound_var("r", n_type)
    var suc = s.import_symbol(nat.get(NatName.SUC).name)
    var zero = s.import_symbol(nat.get(NatName.ZERO).name)
    var step = lambda_(n, lambda_(r, suc(suc(r))))
    var double = define_primrec(s, nat, "demo.double", zero, step, budget)
    print("Zero:", double.zero_eq.statement().format())
    print("Suc:", double.suc_eq.statement().format())
    print("Axioms in double.zero_eq:", len(double.zero_eq.axioms()))

Run from the repository root pixi run mojo run -I src docs/examples/nat/primrec.mojo

Output

Rows: 36 then 41 arithmetic declarations
Induction: nat.induct
Zero: demo.double(nat.zero) = nat.zero
Suc: ∀demo.double.n.1:nat.nat. demo.double(nat.suc(demo.double.n.1)) = (λn:nat.nat. λr:nat.nat. nat.suc(nat.suc(r)))(demo.double.n.1)(demo.double(demo.double.n.1))
Axioms in double.zero_eq: 2

Classical inputs

ClassicalInputs

@fieldwise_init
struct ClassicalInputs(ImplicitlyCopyable)
Field Type Description
epsilon String The choice constant ε[α]: (α → Prop) → α (I1), by name.
choice DagFact The theorem or axiom ∀P x. P x → P (ε P).
funext DagFact The theorem or axiom ∀f g. (∀x. f x = g x) → f = g (I2).
ind String The nullary type of the infinity principle (I3), by name.
infinity DagFact The theorem or axiom stating infinity, in witness or named form.
successor Optional[String] The successor constant of a named form, by name; absent for the witness form.

The classical principles the construction uses, found by statement.

Defined in src/judgment_nat/_dag_inputs.mojo.

recognize

def recognize(d: _DagSession, mut budget: Budget) raises NatError -> ClassicalInputs

Find the classical principles of a session by their statements, as recognize.

Arguments.

  • d: A session with choice, function extensionality, and infinity.
  • budget: The caller's allowance; one unit per candidate and comparison, and the listing's.

Returns. The first matching declarations, in the session's declaration order.

Raises.

  • NatError: MISSING_PRINCIPLE naming an absent principle; LIMIT on exhaustion; KERNEL or LIBRARY for a refusal.

Defined in src/judgment_nat/_dag_inputs.mojo.

The natural numbers

build_nat

def build_nat(d: _DagSession, inputs: ClassicalInputs, mut budget: Budget) raises NatError -> NatTheory

Extend a classical session with the natural numbers, as build_nat.

Arguments.

  • d: A session holding inputs.
  • inputs: The classical principles, from _dag_recognize.
  • budget: The caller's allowance, charged once for the call and once per declaration.

Returns. The 36 rows, their facts retained in the session.

Raises.

  • NatError: WRONG_KERNEL for inputs of another session; LIMIT on exhaustion; KERNEL or LIBRARY for a refusal. On any failure no row of the call survives.

Defined in src/judgment_nat/_dag_theory.mojo.

NatTheory

struct NatTheory(Movable)
Field Type Description
rows List[_DagRow] Each row's name (the specification's by its first constant) and the fact it is used by.
inputs ClassicalInputs The classical principles the rows use.

The natural-number declarations in a session, in order, and the classical principles they use.

Defined in src/judgment_nat/_dag_theory.mojo.

NatTheory.__init__

def __init__(out self, var rows: List[_DagRow], inputs: ClassicalInputs)

Construct a natural-number theory handle from its checked rows and classical inputs.

Arguments.

  • rows: Checked declaration rows in NatName order.
  • inputs: Recognized classical principles used by the construction.

NatTheory.get

def get(self, name: NatName) raises NatError -> _DagRow

One row, as NatTheory.get.

Raises.

  • NatError: SHAPE for a row outside the list.

NatName

@fieldwise_init
struct NatName(Equatable, ImplicitlyCopyable)
Field Type Description
row Int The row's zero-based position; row n of the page is at n - 1.

Name one natural-number declaration.

Defined in src/judgment_nat/_rows.mojo.

NatName.LEAST

comptime LEAST = NatName(0)

The least closed predicate.

NatName.LEAST_ZERO

comptime LEAST_ZERO = NatName(1)

∀z s. least z s z.

NatName.LEAST_SUC

comptime LEAST_SUC = NatName(2)

Closure under the successor.

NatName.LEAST_INDUCT

comptime LEAST_INDUCT = NatName(3)

Induction on a least closed predicate.

NatName.LEAST_INDUCT_ON

comptime LEAST_INDUCT_ON = NatName(4)

Induction with the hypothesis least z s y.

NatName.GRAPH

comptime GRAPH = NatName(5)

The recursion graph.

NatName.GRAPH_ZERO

comptime GRAPH_ZERO = NatName(6)

The graph contains (z, a).

NatName.GRAPH_SUC

comptime GRAPH_SUC = NatName(7)

The graph's closure.

NatName.GRAPH_LEAST

comptime GRAPH_LEAST = NatName(8)

The graph's domain lies in least z s.

NatName.GRAPH_CASES

comptime GRAPH_CASES = NatName(9)

Inversion of the graph.

NatName.GRAPH_UNIQUE

comptime GRAPH_UNIQUE = NatName(10)

Existence and uniqueness of graph values.

NatName.RECURSOR

comptime RECURSOR = NatName(11)

The recursor, by choice.

NatName.RECURSOR_ZERO

comptime RECURSOR_ZERO = NatName(12)

The recursor's zero equation.

NatName.RECURSOR_SUC

comptime RECURSOR_SUC = NatName(13)

The recursor's successor equation.

NatName.RECURSOR_UNIQUE

comptime RECURSOR_UNIQUE = NatName(14)

Uniqueness of the recursor.

NatName.IND_WITNESS

comptime IND_WITNESS = NatName(15)

The witness of the representatives' specification.

NatName.REPS

comptime REPS = NatName(16)

The specification of nat.suc_rep and nat.zero_rep.

NatName.NAT_WITNESS

comptime NAT_WITNESS = NatName(17)

The witness of the type definition.

NatName.NAT

comptime NAT = NatName(18)

The type definition of nat.nat.

NatName.ZERO

comptime ZERO = NatName(19)

nat.zero.

NatName.SUC

comptime SUC = NatName(20)

nat.suc.

NatName.REP_LEAST

comptime REP_LEAST = NatName(21)

Representatives are least.

NatName.REP_ZERO

comptime REP_ZERO = NatName(22)

rep zero = zero_rep.

NatName.REP_SUC

comptime REP_SUC = NatName(23)

rep (suc n) = suc_rep (rep n).

NatName.SUC_INJECT

comptime SUC_INJECT = NatName(24)

The successor is injective.

NatName.SUC_NE_ZERO

comptime SUC_NE_ZERO = NatName(25)

No successor is zero.

NatName.LEAST_NAT

comptime LEAST_NAT = NatName(26)

Every natural number is least.

NatName.INDUCT

comptime INDUCT = NatName(27)

Induction on nat.nat.

NatName.CASES

comptime CASES = NatName(28)

Every number is zero or a successor.

NatName.REC

comptime REC = NatName(29)

Primitive recursion on nat.nat.

NatName.REC_ZERO

comptime REC_ZERO = NatName(30)

rec a f zero = a.

NatName.REC_SUC

comptime REC_SUC = NatName(31)

rec a f (suc n) = f n (rec a f n).

NatName.REC_UNIQUE

comptime REC_UNIQUE = NatName(32)

Uniqueness of primitive recursion.

NatName.EMBED_LEAST

comptime EMBED_LEAST = NatName(33)

The embedding lands in least z s.

NatName.EMBED_ONTO

comptime EMBED_ONTO = NatName(34)

The embedding reaches least z s.

NatName.EMBED_INJECT

comptime EMBED_INJECT = NatName(35)

The embedding is injective.

Primitive recursion and arithmetic

define_primrec

def define_primrec(d: _DagSession, nat: NatTheory, name: String, a: DagExpr, f: DagExpr, mut budget: Budget) raises NatError -> Primrec

Define name := rec[β] a f with its recursion equations (Definition NR-6), as define_primrec.

Arguments.

  • d: The session holding the natural numbers.
  • nat: The natural numbers, from build_nat.
  • name: The new constant's qualified name; name.zero and name.suc name its equations.
  • a: A closed base a: β.
  • f: A closed step f: nat → β → β; the type variables of a and f occur in β.
  • budget: The caller's allowance.

Returns. The definition's equation and both equations, retained in the session.

Raises.

  • NatError: SHAPE for an open term, mismatched types, a type variable absent from β, or natural numbers that are not this session's rows (_dag_validated); NAME for a name in use; WRONG_KERNEL for a term or row of another session; LIMIT; LIBRARY for another refusal. Nothing is declared on failure.

Defined in src/judgment_nat/_dag_primrec.mojo.

Primrec

@fieldwise_init
struct Primrec(Copyable, Movable)
Field Type Description
constant DagFact The definition's equation c = rec[β] a f.
zero_eq DagFact The theorem c zero = a.
suc_eq DagFact The theorem ∀n. c (suc n) = f n (c n).

A primitive recursive definition and its two equations, as Primrec.

Defined in src/judgment_nat/_dag_primrec.mojo.

build_arithmetic

def build_arithmetic(d: _DagSession, nat: NatTheory, mut budget: Budget) raises NatError -> NatArithmetic

Declare the arithmetic of Definition NR-7 and the laws of Theorem NR-7, as build_arithmetic.

Arguments.

  • d: The session holding the natural numbers.
  • nat: The natural numbers, from build_nat.
  • budget: The caller's allowance.

Returns. The 41 rows, their facts retained in the session.

Raises.

  • NatError: SHAPE or WRONG_KERNEL for natural numbers that are not this session's rows (_dag_validated); NAME when an arithmetic name is in use; LIMIT on exhaustion; KERNEL or LIBRARY for a refusal. On any failure no row of the call survives.

Defined in src/judgment_nat/_dag_arithmetic.mojo.

NatArithmetic

struct NatArithmetic(Movable)
Field Type Description
names List[String] The rows' names, in order.
facts List[DagFact] Each row's fact: a definition's equation, a theorem's own.

The arithmetic rows, in order, with their names, as NatArithmetic.

Defined in src/judgment_nat/_dag_arithmetic.mojo.

NatArithmetic.__init__

def __init__(out self, var names: List[String], var facts: List[DagFact])

Construct a natural-number arithmetic handle from its declaration names and checked facts.

Arguments.

  • names: Arithmetic declaration names in their declared order.
  • facts: Corresponding checked fact handles.

NatArithmetic.get

def get(self, name: String) raises NatError -> DagFact

A row's fact by name, as NatArithmetic.get.

Raises.

  • NatError: NAME when no arithmetic row has the name.

Bridges

nat_bridge

def nat_bridge(d: _DagSession, nat: NatTheory, name: String, ty: DagType, zero: DagExpr, successor: DagExpr, inject: DagFact, distinct: DagFact, induct: DagFact, mut budget: Budget) raises NatError -> NatBridge

Relate nat.nat to a structure with zero, successor, and induction by checked inverse maps, as nat_bridge.

Arguments.

  • d: The session holding the natural numbers and the premises.
  • nat: The natural numbers, from build_nat.
  • name: The prefix of the eight declarations.
  • ty: The structure's monomorphic type t.
  • zero: Its closed zero z: t.
  • successor: Its closed successor s: t → t.
  • inject: An axiom or theorem stating exactly ∀x y. s x = s y → x = y.
  • distinct: An axiom or theorem stating exactly ∀x. ¬ s x = z.
  • induct: An axiom or theorem stating exactly ∀P. P z → (∀n. P n → P (s n)) → ∀n. P n.
  • budget: The caller's allowance.

Returns. The two maps and their six laws, retained in the session. to_zero and to_suc rest on no premise, to_from on induction, the other three on all three.

Raises.

  • NatError: SHAPE for a premise with another statement, ill-typed terms, or natural numbers that are not this session's rows (_dag_validated); NAME; WRONG_KERNEL for a type, term, premise or row of another session; LIMIT; KERNEL or LIBRARY for a refusal. Nothing is declared on failure.

Defined in src/judgment_nat/_dag_bridge.mojo.

NatBridge

@fieldwise_init
struct NatBridge(Copyable, Movable)
Field Type Description
to DagFact name.to = rec z (λn y. s y), opaque: nat.nat → τ.
from_ DagFact name.from = λx. ε (λn. name.to n = x), opaque: τ → nat.nat.
to_zero DagFact name.to zero = z.
to_suc DagFact ∀n. name.to (suc n) = s (name.to n).
from_to DagFact ∀n. name.from (name.to n) = n.
to_from DagFact ∀x. name.to (name.from x) = x.
from_zero DagFact name.from z = zero.
from_suc DagFact ∀x. name.from (s x) = suc (name.from x).

The two maps of a bridge and their laws, as NatBridge: each definition by its equation.

Defined in src/judgment_nat/_dag_bridge.mojo.

Errors

NatError

struct NatError(Copyable, Movable, Writable)
Field Type Description
kind NatErrorKind The package's classification of the failure.
message String A description for people; clients branch on the kinds.
kernel_kind Optional[ErrorKind] The kernel kind of a KERNEL refusal, or of a library refusal that wraps one.

Carry a package failure and, for a kernel refusal, its original kind.

Defined in src/judgment_nat/errors.mojo.

NatError.__init__

def __init__(out self, kind: NatErrorKind, message: String, kernel_kind: Optional[ErrorKind] = None)

Make an error with explicit provenance.

Arguments.

  • kind: The error kind.
  • message: The failure's description.
  • kernel_kind: The original kernel kind, if any.

NatError.__init__

@implicit
def __init__(out self, error: KernelError)

Wrap a kernel refusal as KERNEL, or LIMIT for an exhausted kernel budget.

Arguments.

  • error: The kernel refusal to preserve.

NatError.__init__

@implicit
def __init__(out self, error: LibError)

Wrap a library refusal as LIBRARY, LIMIT for exhaustion, or KERNEL for a wrapped kernel refusal.

Arguments.

  • error: The library refusal to preserve.

NatError.write_to

def write_to(self, mut writer: Some[Writer])

Write the kind, optional kernel kind, and message.

Arguments.

  • writer: The writer receiving the diagnostic.

NatErrorKind

@fieldwise_init
struct NatErrorKind(Equatable, ImplicitlyCopyable, Writable)
Field Type Description
code UInt8 The kind's internal number; compare named kinds, not these numbers.

Classify a failure of the natural-number package.

Defined in src/judgment_nat/errors.mojo.

NatErrorKind.MISSING_PRINCIPLE

comptime MISSING_PRINCIPLE = NatErrorKind(1)

The theory lacks a classical principle recognized by its statement.

NatErrorKind.SHAPE

comptime SHAPE = NatErrorKind(2)

An argument has the wrong type, is open, or violates a type-variable condition.

NatErrorKind.NAME

comptime NAME = NatErrorKind(3)

A name the call would declare is already in use.

NatErrorKind.LIMIT

comptime LIMIT = NatErrorKind(4)

The caller's budget is exhausted.

NatErrorKind.WRONG_KERNEL

comptime WRONG_KERNEL = NatErrorKind(5)

A package value belongs to another kernel.

NatErrorKind.KERNEL

comptime KERNEL = NatErrorKind(6)

The kernel refused an operation; kernel_kind records why.

NatErrorKind.LIBRARY

comptime LIBRARY = NatErrorKind(7)

judgment_shell refused an operation; the message records why.

NatErrorKind.write_to

def write_to(self, mut writer: Some[Writer])

Write the kind's name.

Arguments.

  • writer: The writer receiving the name.
judgment v1.0.0 for Mojo 1.2 · Apache License 2.0 with LLVM Exceptions · Source on GitHub