Proofs from Python¶
The judgment Python package calls the compiled prebuilt core
through ctypes on Linux and macOS. There is no Mojo extension build, no
per-script compilation, and startup takes about 30 ms.
It exposes the same facade as Mojo with matching names, defaults, and operators,
along with Python keyword arguments, arbitrary-precision ints, and
fractions.Fraction rationals.
Python tutorial track
Every core, Scalar, and Store lesson in the Tutorials includes a runnable Python version via the language toggle.
Requirements¶
- Platform: Linux (
x86_64,aarch64, glibc 2.34+) or Apple Silicon macOS (arm64). - From PyPI (recommended for Python): Python 3.10+ with
piporuv—pip install judgment-proverinstallsimport judgment, the full Store-enabledlibjudgment_store, andjudgment-fetch-mathlibwith no Pixi, noPYTHONPATH, and noJUDGMENT_CORE. - From
modular-community(once merged):pixi add judgmentinstallslibjudgment_store, the Mojo client, and the Python package ready to import (pixi run python my_proof.py). - From a source checkout: Pixi and a one-time core build of ~40–50 minutes on 4 cores (~10 GB RAM with 2 workers, or ~5 GB with
--jobs 1), cached under.cache/prebuilt-core/. After that, Python starts in ~30 ms and calls straight into the shared library without compiling anything.
1. Install or build the core¶
From PyPI (pip / uv)¶
pip install judgment-prover
python -c "import judgment; s = judgment.Session(); print(s.prop('P').format())"
With Pixi (modular-community)¶
Once the modular-community pull request merges:
pixi add judgment
pixi run python -c "import judgment; s = judgment.Session(); print(s.prop('P').format())"
From a source checkout¶
git clone https://github.com/Spellbound-Mojo/judgment.git
cd judgment
pixi install --locked
pixi run build-core
pixi run build-core builds the packages, compiles the 23 core shim parts, and
links .cache/prebuilt-core/lib/libjudgment.so (or libjudgment.dylib on macOS).
On a lower-memory machine, run
pixi run build && pixi run python bindings/build_core.py --jobs 1. Later runs
only recompile parts whose inputs changed.
If you also want binary libraries, OpenTheory articles, and theory interpretations, build the Store variant (~3 extra minutes, reusing the compiled default parts):
pixi run build-core-store
import judgment loads libjudgment_store automatically when it is up to date
(at least as new as libjudgment and matching the current Store packages).
Otherwise it falls back to libjudgment, and Store calls raise JudgmentError
with LibErrorKind.UNSUPPORTED.
2. Run your first Python proof¶
Put bindings/python on PYTHONPATH and run an example:
PYTHONPATH=bindings/python pixi run python docs/examples/python/first_proof.py
Proved: (P and Q) implies (Q and P)
Remaining hypotheses: 0
Here is a short standalone script (my_proof.py) that proves a theorem and then
triggers a kernel refusal:
from judgment import ErrorKind, JudgmentError, Session, implies
s = Session()
p, q = s.prop("P"), s.prop("Q")
proof = s.proof()
premise = proof.assume(p & q)
theorem = proof.finish(proof.conjoin(proof.right(premise), proof.left(premise)))
print(theorem.statement().same_as(implies(p & q, q & p)), theorem)
try:
s.prop("P")
except JudgmentError as e:
print(e.kind, e.kernel_kind == ErrorKind.NAME_CLASH, e)
PYTHONPATH=bindings/python pixi run python my_proof.py
True ⊢ P ∧ Q → Q ∧ P
KERNEL True KERNEL(NAME_CLASH): the constant P: a constant named P is already declared
Using your own system Python¶
Any compatible CPython on the same machine (3.13+ checked) can import judgment
by pointing JUDGMENT_CORE at the built shared library:
JUDGMENT_CORE=$PWD/.cache/prebuilt-core/lib/libjudgment.so \
PYTHONPATH=bindings/python python3 my_proof.py
On macOS, point JUDGMENT_CORE at libjudgment.dylib (or
libjudgment_store.dylib). Keep the shared library in .cache/prebuilt-core/lib/
so it can find its Pixi Mojo runtime.
3. Binary libraries, OpenTheory, and theory interpretations¶
With pixi run build-core-store built, Python supports the synchronous Store API:
creating and updating binary libraries (Library, LibraryChange), reading and
writing OpenTheory v6 articles (Article, write_article), and transporting
checked proofs between theories (TypeImage, prepare_interpretation,
transport_type, transport_term, reuse).
See Lesson 5.4: Save and reopen a binary library, Lesson 5.7: Exchange proofs with OpenTheory, Lesson 5.8: Verify an exported proof in Isabelle/HOL, and Lesson 5.9: Transport theorems with interpretations.
Read a published library¶
The load_library.py example below reads a fixture library written by a small
Mojo helper binary:
pixi run build-core-store
pixi run mojo build -I build -I docs/examples/store bindings/python/tests/example_library.mojo -o .cache/example_library
.cache/example_library .cache/example-library
JUDGMENT_EXAMPLE_LIBRARY=.cache/example-library PYTHONPATH=bindings/python pixi run python docs/examples/python/store/load_library.py
Run the client test suite¶
pixi run core-test
This builds or reuses both core variants, runs the Python and Mojo client tests,
and checks all Python documentation examples. If a shared library does not match
the generated client's ABI or generator hash, import judgment fails immediately
with an ImportError telling you what to rebuild.
What differs from Mojo¶
Most examples translate line for line, with a few Python-specific details to keep in mind:
| Topic | Python behavior |
|---|---|
| Errors | Core refusals raise JudgmentError(kind, kernel_kind, message) (str(e) matches Mojo's LibError). Store catalog and publication refusals raise StoreError(kind, message, offset). |
| Expression equality | a == b builds a HOL equation Expr, just like in Mojo. Expressions set __hash__ = None and raise TypeError on bool(e) to catch accidental != or if e:. Use a.same_as(b) to compare handles. |
| Exact numbers | Arbitrary-precision integers are ordinary Python ints of any size; rationals are fractions.Fraction (plain ints are also accepted). ComplexBall exposes exact rational real_mid, real_rad, imag_mid, and imag_rad. |
Records and Budget |
Records (ExactValue, ScalarAtom, TypeImage, TheoremInfo, Identity, …) are plain value objects. Budget(n) updates .remaining in place on both success and failure. |
| Overloads | Overloaded Mojo methods map to one Python method that dispatches on runtime argument types. |
| Memory and lifetimes | Each Session owns a ~35 MB workspace, so reuse sessions instead of allocating thousands at once. Session-owned handles keep their Session alive automatically, and GC finalizers queue deferred frees safely without causing BUSY. |
Threads and fork |
ctypes releases the GIL during core calls, but each Session, object (ScalarProfile, Library, …), or Budget serves one call at a time (concurrent calls raise BUSY; non-raising accessors wait). Handles cannot be pickled, and processes forked after import judgment refuse calls; use multiprocessing with "spawn". |
Examples¶
Each program is the Python port of a Mojo example and prints exactly what it prints.
Check a proposed substitution, preserve its guard, and retain a reusable theorem¶
Mojo
"""Check a proposed substitution, preserve its guard, and retain a reusable theorem."""
from std.testing import assert_true
from judgment import Session, arrow, implies
from judgment_shell import LibErrorKind
def main() raises:
var s = Session()
var a_type = s.declare_type("A")
var a = s.symbol("a", a_type)
var b = s.symbol("b", a_type)
var c = s.symbol("c", a_type)
var f = s.symbol("f", arrow(a_type, a_type))
var tx = s.transaction()
var outer = s.base()
var guard = a == b
var assumed = s.assume(outer, guard, "ab")
var input = f(a)
var candidate = f(b)
var expected = input == candidate
# Check congruence under the guard hypothesis a = b.
var same_function = s.eq_refl(assumed, f)
var argument_equality = s.hypothesis(assumed)
var checked = s.congruence(same_function, [argument_equality])
assert_true(checked.statement().same_as(expected))
assert_true(len(checked.hypotheses()) == 1)
assert_true(checked.hypotheses()[0].same_as(guard))
# The same evidence cannot justify a different replacement.
var wrong = input == f(c)
var rejected = False
try:
_ = s.convert(checked, wrong)
except e:
rejected = e.kind == LibErrorKind.KERNEL
assert_true(rejected)
var exported = s.imp_intro(assumed, checked)
var conditional = implies(guard, expected)
assert_true(exported.statement().same_as(conditional))
assert_true(len(exported.hypotheses()) == 0)
var saved = s.prove_step("rewrite_f", exported)
var retained = tx.commit(expressions=[a, b, f], facts=[saved])
# Use retained handles and look up the saved theorem; do not reuse old inner handles.
var ra = retained.expressions()[0]
var rb = retained.expressions()[1]
var rf = retained.expressions()[2]
var theorem = s.fact("rewrite_f")
var context = s.base()
var rule = s.use(context, theorem)
var final_guard = ra == rb
var final_expected = rf(ra) == rf(rb)
assert_true(rule.statement().same_as(implies(final_guard, final_expected)))
assert_true(len(theorem.axioms()) == 0)
var premise = s.assume(context, final_guard, "guard")
var result = s.imp_elim(s.lift_to(rule, premise), s.hypothesis(premise))
assert_true(result.statement().same_as(final_expected))
assert_true(len(result.hypotheses()) == 1)
assert_true(result.hypotheses()[0].same_as(final_guard))
print("Accepted: f(a) = f(b), under a = b")
print("Rejected: the same evidence for f(a) = f(c)")
print("Retained theorem: a = b implies f(a) = f(b)")
print("Reuse still requires evidence for a = b")
Run from the repository root pixi run mojo run -I src docs/examples/certified_rewrite.mojo
Output
Accepted: f(a) = f(b), under a = b
Rejected: the same evidence for f(a) = f(c)
Retained theorem: a = b implies f(a) = f(b)
Reuse still requires evidence for a = b
Python
"""Check a proposed substitution, preserve its guard, and retain a reusable theorem."""
from judgment import Session, arrow, implies, JudgmentError
from judgment import LibErrorKind
def main():
s = Session()
a_type = s.declare_type("A")
a = s.symbol("a", a_type)
b = s.symbol("b", a_type)
c = s.symbol("c", a_type)
f = s.symbol("f", arrow(a_type, a_type))
tx = s.transaction()
outer = s.base()
guard = a == b
assumed = s.assume(outer, guard, "ab")
input = f(a)
candidate = f(b)
expected = input == candidate
# Check congruence under the guard hypothesis a = b.
same_function = s.eq_refl(assumed, f)
argument_equality = s.hypothesis(assumed)
checked = s.congruence(same_function, [argument_equality])
assert checked.statement().same_as(expected)
assert len(checked.hypotheses()) == 1
assert checked.hypotheses()[0].same_as(guard)
# The same evidence cannot justify a different replacement.
wrong = input == f(c)
rejected = False
try:
_ = s.convert(checked, wrong)
except JudgmentError as e:
rejected = e.kind == LibErrorKind.KERNEL
assert rejected
exported = s.imp_intro(assumed, checked)
conditional = implies(guard, expected)
assert exported.statement().same_as(conditional)
assert len(exported.hypotheses()) == 0
saved = s.prove_step("rewrite_f", exported)
retained = tx.commit(expressions=[a, b, f], facts=[saved])
# Use retained handles and look up the saved theorem; do not reuse old inner handles.
ra = retained.expressions()[0]
rb = retained.expressions()[1]
rf = retained.expressions()[2]
theorem = s.fact("rewrite_f")
context = s.base()
rule = s.use(context, theorem)
final_guard = ra == rb
final_expected = rf(ra) == rf(rb)
assert rule.statement().same_as(implies(final_guard, final_expected))
assert len(theorem.axioms()) == 0
premise = s.assume(context, final_guard, "guard")
result = s.imp_elim(s.lift_to(rule, premise), s.hypothesis(premise))
assert result.statement().same_as(final_expected)
assert len(result.hypotheses()) == 1
assert result.hypotheses()[0].same_as(final_guard)
print("Accepted: f(a) = f(b), under a = b")
print("Rejected: the same evidence for f(a) = f(c)")
print("Retained theorem: a = b implies f(a) = f(b)")
print("Reuse still requires evidence for a = b")
if __name__ == "__main__":
main()
Run from the repository root PYTHONPATH=bindings/python:docs/examples/python pixi run python docs/examples/python/certified_rewrite.py
Output
Accepted: f(a) = f(b), under a = b
Rejected: the same evidence for f(a) = f(c)
Retained theorem: a = b implies f(a) = f(b)
Reuse still requires evidence for a = b
Check a proof against its promised conclusion and reject a mismatch¶
Mojo
"""Check a proof against its promised conclusion and reject a mismatch."""
from std.testing import assert_true
from judgment import Fact, Proof, Session, Step
from judgment_shell import LibErrorKind
def main() raises:
var s = Session()
var root = s.base()
var truth = s.true_()
var falsehood = s.false_()
var expected = truth & truth
var leaf: Step = s.truth(root)
var both: Step = s.and_intro(leaf, leaf)
assert_true(both.statement().same_as(expected))
assert_true(len(both.hypotheses()) == 0)
var proof: Proof = s.theorem("both_true", expected)
proof.exact(both)
var checked: Fact = proof.finish()
assert_true(checked.statement().same_as(expected))
assert_true(len(checked.axioms()) == 0)
var rejected = False
try:
var wrong = s.theorem("wrong_goal", falsehood)
wrong.exact(both)
except e:
rejected = e.kind == LibErrorKind.KERNEL or e.kind == LibErrorKind.SHAPE
assert_true(rejected)
print("Accepted theorem: True and True")
print("Rejected promised conclusion: False")
Run from the repository root pixi run mojo run -I src docs/examples/checking_proofs.mojo
Output
Accepted theorem: True and True
Rejected promised conclusion: False
Python
"""Check a proof against its promised conclusion and reject a mismatch."""
from judgment import Fact, Proof, Session, Step, JudgmentError
from judgment import LibErrorKind
def main():
s = Session()
root = s.base()
truth = s.true_()
falsehood = s.false_()
expected = truth & truth
leaf = s.truth(root)
both = s.and_intro(leaf, leaf)
assert both.statement().same_as(expected)
assert len(both.hypotheses()) == 0
proof = s.theorem("both_true", expected)
proof.exact(both)
checked = proof.finish()
assert checked.statement().same_as(expected)
assert len(checked.axioms()) == 0
rejected = False
try:
wrong = s.theorem("wrong_goal", falsehood)
wrong.exact(both)
except JudgmentError as e:
rejected = e.kind == LibErrorKind.KERNEL or e.kind == LibErrorKind.SHAPE
assert rejected
print("Accepted theorem: True and True")
print("Rejected promised conclusion: False")
if __name__ == "__main__":
main()
Run from the repository root PYTHONPATH=bindings/python:docs/examples/python pixi run python docs/examples/python/checking_proofs.py
Output
Accepted theorem: True and True
Rejected promised conclusion: False
Compare transparent and opaque definitions and save a proven equation¶
Mojo
"""Compare transparent and opaque definitions and save a proven equation."""
from std.testing import assert_true
from judgment import Session
from judgment_shell import LibErrorKind
def main() raises:
var s = Session()
var truth = s.true_()
var absent = False
try:
_ = s.fact("Hidden")
except e:
absent = e.kind == LibErrorKind.NO_MATCH
assert_true(absent)
var visible = s.define("Visible", truth, transparent=True)
var hidden = s.define("Hidden", truth, transparent=False)
var visible_term = visible.symbol()
var hidden_term = hidden.symbol()
assert_true(not visible_term.same_as(truth))
# A transparent definition unfolds during explicit conversion.
var by_conv = s.theorem("visible_is_true", visible_term == truth)
by_conv.change(truth == truth, unfold=[visible])
by_conv.rfl()
var visible_fact = by_conv.finish()
assert_true(visible_fact.statement().same_as(visible_term == truth))
# Without explicit unfolding, and for opaque definitions, conversion refuses.
var no_unfold = False
try:
var blocked = s.theorem("visible_no_unfold", visible_term == truth)
blocked.change(truth == truth)
except e:
no_unfold = e.kind == LibErrorKind.KERNEL or e.kind == LibErrorKind.SHAPE
assert_true(no_unfold)
var opaque_blocked = False
try:
var blocked = s.theorem("hidden_by_conv", hidden_term == truth)
blocked.change(truth == truth, unfold=[hidden])
except e:
opaque_blocked = e.kind == LibErrorKind.KERNEL or e.kind == LibErrorKind.SHAPE
assert_true(opaque_blocked)
# Even an opaque definition supplies a checked defining equation.
var equation = hidden.equation()
var expected = hidden_term == truth
assert_true(equation.statement().same_as(expected))
var saved_proof = s.theorem("hidden_is_true", expected)
saved_proof.exact(equation)
var saved = saved_proof.finish()
var reused = s.fact("hidden_is_true")
assert_true(saved.statement().same_as(expected))
assert_true(reused.statement().same_as(expected))
assert_true(len(reused.axioms()) == 0)
print("Transparent definition: equal by conversion")
print("Opaque definition: equation proved, saved, and reused")
Run from the repository root pixi run mojo run -I src docs/examples/definitions.mojo
Output
Transparent definition: equal by conversion
Opaque definition: equation proved, saved, and reused
Python
"""Compare transparent and opaque definitions and save a proven equation."""
from judgment import Session, JudgmentError
from judgment import LibErrorKind
def main():
s = Session()
truth = s.true_()
absent = False
try:
_ = s.fact("Hidden")
except JudgmentError as e:
absent = e.kind == LibErrorKind.NO_MATCH
assert absent
visible = s.define("Visible", truth, transparent=True)
hidden = s.define("Hidden", truth, transparent=False)
visible_term = visible.symbol()
hidden_term = hidden.symbol()
assert not visible_term.same_as(truth)
# A transparent definition unfolds during explicit conversion.
by_conv = s.theorem("visible_is_true", visible_term == truth)
by_conv.change(truth == truth, unfold=[visible])
by_conv.rfl()
visible_fact = by_conv.finish()
assert visible_fact.statement().same_as(visible_term == truth)
# Without explicit unfolding, and for opaque definitions, conversion refuses.
no_unfold = False
try:
blocked = s.theorem("visible_no_unfold", visible_term == truth)
blocked.change(truth == truth)
except JudgmentError as e:
no_unfold = e.kind == LibErrorKind.KERNEL or e.kind == LibErrorKind.SHAPE
assert no_unfold
opaque_blocked = False
try:
blocked = s.theorem("hidden_by_conv", hidden_term == truth)
blocked.change(truth == truth, unfold=[hidden])
except JudgmentError as e:
opaque_blocked = e.kind == LibErrorKind.KERNEL or e.kind == LibErrorKind.SHAPE
assert opaque_blocked
# Even an opaque definition supplies a checked defining equation.
equation = hidden.equation()
expected = hidden_term == truth
assert equation.statement().same_as(expected)
saved_proof = s.theorem("hidden_is_true", expected)
saved_proof.exact(equation)
saved = saved_proof.finish()
reused = s.fact("hidden_is_true")
assert saved.statement().same_as(expected)
assert reused.statement().same_as(expected)
assert len(reused.axioms()) == 0
print("Transparent definition: equal by conversion")
print("Opaque definition: equation proved, saved, and reused")
if __name__ == "__main__":
main()
Run from the repository root PYTHONPATH=bindings/python:docs/examples/python pixi run python docs/examples/python/definitions.py
Output
Transparent definition: equal by conversion
Opaque definition: equation proved, saved, and reused
Prove that a conjunction can be swapped without adding an axiom¶
Mojo
"""Prove that a conjunction can be swapped without adding an axiom."""
from std.testing import assert_true
from judgment import Session, implies
def main() raises:
var s = Session()
var p = s.prop("P")
var q = s.prop("Q")
var p_and_q = p & q
var q_and_p = q & p
var expected = implies(p_and_q, q_and_p)
var forward = s.proof()
var premise = forward.assume(p_and_q)
var swapped = forward.conjoin(forward.right(premise), forward.left(premise))
var theorem = forward.finish(swapped)
assert_true(theorem.statement().same_as(expected))
assert_true(len(theorem.hypotheses()) == 0)
assert_true(len(theorem.axioms()) == 0)
print("Proved: (P and Q) implies (Q and P)")
print("Remaining hypotheses: 0")
Run from the repository root pixi run core-run docs/examples/first_proof.mojo
Output
Proved: (P and Q) implies (Q and P)
Remaining hypotheses: 0
Python
"""Prove that a conjunction can be swapped without adding an axiom."""
from judgment import Session, implies
def main():
s = Session()
p = s.prop("P")
q = s.prop("Q")
p_and_q = p & q
q_and_p = q & p
expected = implies(p_and_q, q_and_p)
forward = s.proof()
premise = forward.assume(p_and_q)
swapped = forward.conjoin(forward.right(premise), forward.left(premise))
theorem = forward.finish(swapped)
assert theorem.statement().same_as(expected)
assert len(theorem.hypotheses()) == 0
assert len(theorem.axioms()) == 0
print("Proved: (P and Q) implies (Q and P)")
print("Remaining hypotheses: 0")
if __name__ == "__main__":
main()
Run from the repository root PYTHONPATH=bindings/python:docs/examples/python pixi run python docs/examples/python/first_proof.py
Output
Proved: (P and Q) implies (Q and P)
Remaining hypotheses: 0
Build a lambda and reuse a quantified theorem at different types¶
Mojo
"""Build a lambda and reuse a quantified theorem at different types."""
from std.testing import assert_true
from judgment import Session, arrow, forall, lambda_
from judgment_shell import LibErrorKind
def main() raises:
var s = Session()
var alpha = s.type_var("a")
var bx = s.bound_var("x", alpha)
var identity = lambda_(bx, bx)
var proof = s.theorem("identity_refl")
var a = proof.type_var("a")
var x = proof.var("x", a)
var v = proof.bound_var("v", a)
var id_a = lambda_(v, v)
var applied = id_a(x)
assert_true(applied.same_as(x))
proof.goal(applied == x)
proof.rfl()
var saved = proof.finish()
var params = saved.type_params()
assert_true(len(params) == 1)
assert_true(len(saved.axioms()) == 0)
var py = s.bound_var("y", params[0])
assert_true(saved.statement().same_as(forall(py, py == py)))
var root = s.base()
var prop = s.prop_type()
var truth = s.true_()
var instance = s.use(root, saved, terms=[truth], type_args=[prop])
assert_true(instance.statement().same_as(truth == truth))
var functions = arrow(alpha, alpha)
var at_function = s.use(root, saved, terms=[identity], type_args=[functions])
assert_true(at_function.statement().same_as(identity == identity))
var rejected = False
try:
_ = s.use(root, saved, terms=[truth])
except e:
rejected = e.kind == LibErrorKind.KERNEL or e.kind == LibErrorKind.SHAPE
assert_true(rejected)
print("Lambda application: (lambda x. x)(x) = x")
print("Saved scheme: for every x of type a, x = x")
print("Reused at Prop and at a function type")
print("Missing type argument: rejected")
Run from the repository root pixi run mojo run -I src docs/examples/quantified_theorem.mojo
Output
Lambda application: (lambda x. x)(x) = x
Saved scheme: for every x of type a, x = x
Reused at Prop and at a function type
Missing type argument: rejected
Python
"""Build a lambda and reuse a quantified theorem at different types."""
from judgment import Session, arrow, forall, lambda_, JudgmentError
from judgment import LibErrorKind
def main():
s = Session()
alpha = s.type_var("a")
bx = s.bound_var("x", alpha)
identity = lambda_(bx, bx)
proof = s.theorem("identity_refl")
a = proof.type_var("a")
x = proof.var("x", a)
v = proof.bound_var("v", a)
id_a = lambda_(v, v)
applied = id_a(x)
assert applied.same_as(x)
proof.goal(applied == x)
proof.rfl()
saved = proof.finish()
params = saved.type_params()
assert len(params) == 1
assert len(saved.axioms()) == 0
py = s.bound_var("y", params[0])
assert saved.statement().same_as(forall(py, py == py))
root = s.base()
prop = s.prop_type()
truth = s.true_()
instance = s.use(root, saved, terms=[truth], type_args=[prop])
assert instance.statement().same_as(truth == truth)
functions = arrow(alpha, alpha)
at_function = s.use(root, saved, terms=[identity], type_args=[functions])
assert at_function.statement().same_as(identity == identity)
rejected = False
try:
_ = s.use(root, saved, terms=[truth])
except JudgmentError as e:
rejected = e.kind == LibErrorKind.KERNEL or e.kind == LibErrorKind.SHAPE
assert rejected
print("Lambda application: (lambda x. x)(x) = x")
print("Saved scheme: for every x of type a, x = x")
print("Reused at Prop and at a function type")
print("Missing type argument: rejected")
if __name__ == "__main__":
main()
Run from the repository root PYTHONPATH=bindings/python:docs/examples/python pixi run python docs/examples/python/quantified_theorem.py
Output
Lambda application: (lambda x. x)(x) = x
Saved scheme: for every x of type a, x = x
Reused at Prop and at a function type
Missing type argument: rejected
Retain checked results across transactions, discard scratch work, and check out snapshots¶
Mojo
"""Retain checked results across transactions, discard scratch work, and check out snapshots."""
from std.testing import assert_true
from judgment import Session
from judgment_shell import LibErrorKind
def main() raises:
var s = Session()
var base = s.snapshot()
var tx = s.transaction()
var candidate = s.prop("candidate")
var proof = s.theorem("candidate_refl", candidate == candidate)
proof.rfl()
var old_fact = proof.finish()
var retained = tx.commit(expressions=[candidate], facts=[old_fact])
var kept_term = retained.expressions()[0]
var kept_fact = retained.facts()[0]
var expected = kept_term == kept_term
assert_true(kept_fact.statement().same_as(expected))
assert_true(s.fact("candidate_refl").statement().same_as(expected))
var old_rejected = False
try:
_ = old_fact.statement()
except e:
old_rejected = e.kind == LibErrorKind.KERNEL
assert_true(old_rejected)
var scratch = s.transaction()
var temporary = s.prop("temporary")
scratch.discard()
var discarded_rejected = False
try:
_ = temporary.format()
except e:
discarded_rejected = e.kind == LibErrorKind.KERNEL
assert_true(discarded_rejected)
s.checkout(base)
var rolled_back = False
try:
_ = s.fact("candidate_refl")
except e:
rolled_back = e.kind == LibErrorKind.NO_MATCH
assert_true(rolled_back)
print("Kept proof: candidate = candidate")
print("Old transaction handle: rejected")
print("Discarded transaction handle: rejected")
print("Checked out base snapshot: candidate_refl absent")
Run from the repository root pixi run mojo run -I src docs/examples/scoped_work.mojo
Output
Kept proof: candidate = candidate
Old transaction handle: rejected
Discarded transaction handle: rejected
Checked out base snapshot: candidate_refl absent
Python
"""Retain checked results across transactions, discard scratch work, and check out snapshots."""
from judgment import Session, JudgmentError
from judgment import LibErrorKind
def main():
s = Session()
base = s.snapshot()
tx = s.transaction()
candidate = s.prop("candidate")
proof = s.theorem("candidate_refl", candidate == candidate)
proof.rfl()
old_fact = proof.finish()
retained = tx.commit(expressions=[candidate], facts=[old_fact])
kept_term = retained.expressions()[0]
kept_fact = retained.facts()[0]
expected = kept_term == kept_term
assert kept_fact.statement().same_as(expected)
assert s.fact("candidate_refl").statement().same_as(expected)
old_rejected = False
try:
_ = old_fact.statement()
except JudgmentError as e:
old_rejected = e.kind == LibErrorKind.KERNEL
assert old_rejected
scratch = s.transaction()
temporary = s.prop("temporary")
scratch.discard()
discarded_rejected = False
try:
_ = temporary.format()
except JudgmentError as e:
discarded_rejected = e.kind == LibErrorKind.KERNEL
assert discarded_rejected
s.checkout(base)
rolled_back = False
try:
_ = s.fact("candidate_refl")
except JudgmentError as e:
rolled_back = e.kind == LibErrorKind.NO_MATCH
assert rolled_back
print("Kept proof: candidate = candidate")
print("Old transaction handle: rejected")
print("Discarded transaction handle: rejected")
print("Checked out base snapshot: candidate_refl absent")
if __name__ == "__main__":
main()
Run from the repository root PYTHONPATH=bindings/python:docs/examples/python pixi run python docs/examples/python/scoped_work.py
Output
Kept proof: candidate = candidate
Old transaction handle: rejected
Discarded transaction handle: rejected
Checked out base snapshot: candidate_refl absent
Define a singleton type using a proved nonemptiness witness¶
Mojo
"""Define a singleton type using a proved nonemptiness witness."""
from std.testing import assert_true
from judgment import Session, exists, lambda_
def main() raises:
var s = Session()
var prop = s.prop_type()
var truth = s.true_()
var witness = s.theorem("singleton_exists")
var p = witness.bound_var("p", prop)
var predicate = lambda_(p, p == truth)
witness.goal(exists(p, p == truth))
witness.witness(truth)
witness.rfl()
var inhabited = witness.finish()
assert_true(len(inhabited.axioms()) == 0)
var singleton = s.subset(
"Singleton", predicate, inhabited,
abs_name="abs_singleton", rep_name="rep_singleton",
)
var element = singleton.abstract(truth)
var round_trip = s.forall_elim(s.cite(singleton.abs_rep()), element)
var expected = singleton.abstract(singleton.represent(element)) == element
assert_true(round_trip.statement().same_as(expected))
assert_true(len(round_trip.hypotheses()) == 0)
print("Proved: there exists p:Prop with p = True")
print("Defined Singleton from that nonempty subset")
print("Used generated fact: abs(rep(s)) = s")
Run from the repository root pixi run core-run docs/examples/subset_type.mojo
Output
Proved: there exists p:Prop with p = True
Defined Singleton from that nonempty subset
Used generated fact: abs(rep(s)) = s
Python
"""Define a singleton type using a proved nonemptiness witness."""
from judgment import Session, exists, lambda_
def main():
s = Session()
prop = s.prop_type()
truth = s.true_()
witness = s.theorem("singleton_exists")
p = witness.bound_var("p", prop)
predicate = lambda_(p, p == truth)
witness.goal(exists(p, p == truth))
witness.witness(truth)
witness.rfl()
inhabited = witness.finish()
assert len(inhabited.axioms()) == 0
singleton = s.subset(
"Singleton", predicate, inhabited,
abs_name="abs_singleton", rep_name="rep_singleton",
)
element = singleton.abstract(truth)
round_trip = s.forall_elim(s.cite(singleton.abs_rep()), element)
expected = singleton.abstract(singleton.represent(element)) == element
assert round_trip.statement().same_as(expected)
assert len(round_trip.hypotheses()) == 0
print("Proved: there exists p:Prop with p = True")
print("Defined Singleton from that nonempty subset")
print("Used generated fact: abs(rep(s)) = s")
if __name__ == "__main__":
main()
Run from the repository root PYTHONPATH=bindings/python:docs/examples/python pixi run python docs/examples/python/subset_type.py
Output
Proved: there exists p:Prop with p = True
Defined Singleton from that nonempty subset
Used generated fact: abs(rep(s)) = s
Recognize common Session errors and recover through the public API¶
Mojo
"""Recognize common Session errors and recover through the public API."""
from std.testing import assert_true
from judgment import Session
from judgment_shell import LibError, LibErrorKind
def prove_with_budget(work: UInt64) raises LibError -> Bool:
"""Run a small proof in a session with the chosen work budget."""
var s = Session(work=work)
var truth = s.true_()
var proof = s.theorem("truth_refl", truth == truth)
proof.rfl()
_ = proof.finish()
return True
def main() raises:
var s = Session()
var prop = s.prop_type()
# 1. Looking up a fact before it is declared raises NO_MATCH.
var rejected = False
try:
_ = s.fact("P_refl")
except e:
rejected = e.kind == LibErrorKind.NO_MATCH
assert_true(rejected)
var p = s.prop("P")
var p_proof = s.theorem("P_refl", p == p)
p_proof.rfl()
_ = p_proof.finish()
assert_true(s.fact("P_refl").statement().same_as(p == p))
print("NO_MATCH: declare a fact before looking it up")
# 2. Mixing handles from two different sessions raises WRONG_KERNEL.
var other = Session()
var foreign = other.true_()
rejected = False
try:
_ = s.eq_refl(s.base(), foreign)
except e:
rejected = e.kind == LibErrorKind.WRONG_KERNEL
assert_true(rejected)
assert_true(other.eq_refl(other.base(), foreign).statement().same_as(foreign == foreign))
print("WRONG_KERNEL: use the owning session, or rebuild in the receiving session")
# 3. Using a handle from a discarded transaction raises KERNEL.
var tx = s.transaction()
var old = s.prop("temporary")
tx.discard()
rejected = False
try:
_ = s.eq_refl(s.base(), old)
except e:
rejected = e.kind == LibErrorKind.KERNEL
assert_true(rejected)
# Recovery recreates the constant; old cannot be revived.
var fresh = s.prop("temporary")
assert_true(s.eq_refl(s.base(), fresh).statement().same_as(fresh == fresh))
print("KERNEL: rebuild discarded handles, or retain them in commit")
# 4. Using a fixed local variable in a sibling frame raises KERNEL.
var root = s.base()
var x = s.fix(root, "x", prop)
var y = s.fix(root, "y", prop)
rejected = False
try:
_ = s.eq_refl(y[0], x[1])
except e:
rejected = e.kind == LibErrorKind.KERNEL
assert_true(rejected)
var valid = s.eq_refl(x[0], x[1])
var closed = s.forall_intro(x[0], valid)
assert_true(len(closed.hypotheses()) == 0)
print("KERNEL: prove in the local's frame, then generalize")
# 5. Exhausting the session work allowance raises LIMIT.
rejected = False
try:
_ = prove_with_budget(1)
except e:
rejected = e.kind == LibErrorKind.LIMIT
assert_true(rejected)
assert_true(prove_with_budget(100000))
print("LIMIT: unfinished; a rebuilt request with more work succeeds")
Run from the repository root pixi run mojo run -I src docs/examples/troubleshooting.mojo
Output
NO_MATCH: declare a fact before looking it up
WRONG_KERNEL: use the owning session, or rebuild in the receiving session
KERNEL: rebuild discarded handles, or retain them in commit
KERNEL: prove in the local's frame, then generalize
LIMIT: unfinished; a rebuilt request with more work succeeds
Python
"""Recognize common Session errors and recover through the public API."""
from judgment import Session, JudgmentError
from judgment import JudgmentError, LibErrorKind
def prove_with_budget(work):
"""Run a small proof in a session with the chosen work budget."""
s = Session(work=work)
truth = s.true_()
proof = s.theorem("truth_refl", truth == truth)
proof.rfl()
_ = proof.finish()
return True
def main():
s = Session()
prop = s.prop_type()
# 1. Looking up a fact before it is declared raises NO_MATCH.
rejected = False
try:
_ = s.fact("P_refl")
except JudgmentError as e:
rejected = e.kind == LibErrorKind.NO_MATCH
assert rejected
p = s.prop("P")
p_proof = s.theorem("P_refl", p == p)
p_proof.rfl()
_ = p_proof.finish()
assert s.fact("P_refl").statement().same_as(p == p)
print("NO_MATCH: declare a fact before looking it up")
# 2. Mixing handles from two different sessions raises WRONG_KERNEL.
other = Session()
foreign = other.true_()
rejected = False
try:
_ = s.eq_refl(s.base(), foreign)
except JudgmentError as e:
rejected = e.kind == LibErrorKind.WRONG_KERNEL
assert rejected
assert other.eq_refl(other.base(), foreign).statement().same_as(foreign == foreign)
print("WRONG_KERNEL: use the owning session, or rebuild in the receiving session")
# 3. Using a handle from a discarded transaction raises KERNEL.
tx = s.transaction()
old = s.prop("temporary")
tx.discard()
rejected = False
try:
_ = s.eq_refl(s.base(), old)
except JudgmentError as e:
rejected = e.kind == LibErrorKind.KERNEL
assert rejected
# Recovery recreates the constant; old cannot be revived.
fresh = s.prop("temporary")
assert s.eq_refl(s.base(), fresh).statement().same_as(fresh == fresh)
print("KERNEL: rebuild discarded handles, or retain them in commit")
# 4. Using a fixed local variable in a sibling frame raises KERNEL.
root = s.base()
x = s.fix(root, "x", prop)
y = s.fix(root, "y", prop)
rejected = False
try:
_ = s.eq_refl(y[0], x[1])
except JudgmentError as e:
rejected = e.kind == LibErrorKind.KERNEL
assert rejected
valid = s.eq_refl(x[0], x[1])
closed = s.forall_intro(x[0], valid)
assert len(closed.hypotheses()) == 0
print("KERNEL: prove in the local's frame, then generalize")
# 5. Exhausting the session work allowance raises LIMIT.
rejected = False
try:
_ = prove_with_budget(1)
except JudgmentError as e:
rejected = e.kind == LibErrorKind.LIMIT
assert rejected
assert prove_with_budget(100000)
print("LIMIT: unfinished; a rebuilt request with more work succeeds")
if __name__ == "__main__":
main()
Run from the repository root PYTHONPATH=bindings/python:docs/examples/python pixi run python docs/examples/python/troubleshooting.py
Output
NO_MATCH: declare a fact before looking it up
WRONG_KERNEL: use the owning session, or rebuild in the receiving session
KERNEL: rebuild discarded handles, or retain them in commit
KERNEL: prove in the local's frame, then generalize
LIMIT: unfinished; a rebuilt request with more work succeeds
Library examples¶
Correct a supplied premise, then defer and recover the remaining goal¶
Mojo
"""Correct a supplied premise, then defer and recover the remaining goal."""
from std.testing import assert_equal, assert_true
from judgment_shell import LibErrorKind, Session, implies
def main() raises:
var s = Session()
var join = s.theorem("join")
var Left = join.prop("Left")
var Right = join.prop("Right")
var left = join.given("left", Left)
var right = join.given("right", Right)
join.goal(Left & Right)
join.exact(join.conjoin(left, right))
var conjunction = join.finish()
var P = s.prop("P")
var Q = s.prop("Q")
var target = implies(P & Q, Q & P)
var proof = s.theorem("recover_application", target)
var pair = proof.intro("pair")
var p = proof.left(pair)
var q = proof.right(pair)
# Q & P needs Q first. Supplying P leaves the original goal intact.
var before = proof.format()
try:
_ = proof.apply(conjunction, using=[p])
except error:
assert_equal(error.kind, LibErrorKind.NO_MATCH)
print(error.message)
assert_equal(proof.format(), before)
# Correct the first premise; P remains an explicit obligation.
_ = proof.apply(conjunction, using=[q])
var second = proof.select("premise_2")
second.sorry()
var remaining = proof.obligations()
assert_equal(len(remaining), 1)
assert_true(remaining[0].target().same_as(P))
assert_equal(remaining[0].status(), "deferred")
print("Deferred premise:", remaining[0].path()[0], "requires", remaining[0].target().format())
# Sorry saves unfinished work; it does not supply evidence.
var blocked = False
try:
_ = proof.finish()
except error:
assert_equal(error.kind, LibErrorKind.SHAPE)
blocked = True
assert_true(blocked)
print("Finish blocked:", blocked)
# Recover by name, resume, and supply the checked fact explicitly.
second = proof.select("premise_2")
second.resume()
second.exact(p)
var theorem = proof.finish()
assert_true(theorem.statement().same_as(target))
assert_equal(len(theorem.axioms()), 0)
assert_equal(len(theorem.admissions()), 0)
print(theorem)
Run from the repository root pixi run mojo run -I src docs/examples/library/application_troubleshooting.mojo
Output
apply premise 1: expected Q; supplied P
Deferred premise: premise_2 requires P
Finish blocked: True
⊢ P ∧ Q → Q ∧ P
Python
"""Correct a supplied premise, then defer and recover the remaining goal."""
from judgment import LibErrorKind, Session, implies, JudgmentError
def main():
s = Session()
join = s.theorem("join")
Left = join.prop("Left")
Right = join.prop("Right")
left = join.given("left", Left)
right = join.given("right", Right)
join.goal(Left & Right)
join.exact(join.conjoin(left, right))
conjunction = join.finish()
P = s.prop("P")
Q = s.prop("Q")
target = implies(P & Q, Q & P)
proof = s.theorem("recover_application", target)
pair = proof.intro("pair")
p = proof.left(pair)
q = proof.right(pair)
# Q & P needs Q first. Supplying P leaves the original goal intact.
before = proof.format()
try:
_ = proof.apply(conjunction, using=[p])
except JudgmentError as error:
assert error.kind == LibErrorKind.NO_MATCH
print(error.message)
assert proof.format() == before
# Correct the first premise; P remains an explicit obligation.
_ = proof.apply(conjunction, using=[q])
second = proof.select("premise_2")
second.sorry()
remaining = proof.obligations()
assert len(remaining) == 1
assert remaining[0].target().same_as(P)
assert remaining[0].status() == "deferred"
print("Deferred premise:", remaining[0].path()[0], "requires", remaining[0].target().format())
# Sorry saves unfinished work; it does not supply evidence.
blocked = False
try:
_ = proof.finish()
except JudgmentError as error:
assert error.kind == LibErrorKind.SHAPE
blocked = True
assert blocked
print("Finish blocked:", blocked)
# Recover by name, resume, and supply the checked fact explicitly.
second = proof.select("premise_2")
second.resume()
second.exact(p)
theorem = proof.finish()
assert theorem.statement().same_as(target)
assert len(theorem.axioms()) == 0
assert len(theorem.admissions()) == 0
print(theorem)
if __name__ == "__main__":
main()
Run from the repository root PYTHONPATH=bindings/python:docs/examples/python/library pixi run python docs/examples/python/library/application_troubleshooting.py
Output
apply premise 1: expected Q; supplied P
Deferred premise: premise_2 requires P
Finish blocked: True
⊢ P ∧ Q → Q ∧ P
Use a theorem backward, proving its premises as independent subgoals¶
Mojo
"""Use a theorem backward, proving its premises as independent subgoals."""
from judgment import Session, implies
def main() raises:
var s = Session()
var join = s.theorem("join")
var Left = join.prop("Left")
var Right = join.prop("Right")
var left = join.given("left", Left)
var right = join.given("right", Right)
join.goal(Left & Right)
join.exact(join.conjoin(left, right))
var conjunction = join.finish()
var P = s.prop("P")
var Q = s.prop("Q")
var proof = s.theorem("swap_by_apply", implies(P & Q, Q & P))
var h = proof.intro("pair")
_ = proof.apply(conjunction)
var first = proof.select("premise_1")
var second = proof.select("premise_2")
print("First premise:", first.target().format())
print("Second premise:", second.target().format())
# These can be proved in either order, deferred, or selected later.
second.exact(second.left(h))
first.exact(first.right(h))
var theorem = proof.finish()
print(theorem)
print("Axiom dependencies:", len(theorem.axioms()))
Run from the repository root pixi run core-run docs/examples/library/applying_theorems.mojo
Output
First premise: Q
Second premise: P
⊢ P ∧ Q → Q ∧ P
Axiom dependencies: 0
Python
"""Use a theorem backward, proving its premises as independent subgoals."""
from judgment import Session, implies
def main():
s = Session()
join = s.theorem("join")
Left = join.prop("Left")
Right = join.prop("Right")
left = join.given("left", Left)
right = join.given("right", Right)
join.goal(Left & Right)
join.exact(join.conjoin(left, right))
conjunction = join.finish()
P = s.prop("P")
Q = s.prop("Q")
proof = s.theorem("swap_by_apply", implies(P & Q, Q & P))
h = proof.intro("pair")
_ = proof.apply(conjunction)
first = proof.select("premise_1")
second = proof.select("premise_2")
print("First premise:", first.target().format())
print("Second premise:", second.target().format())
# These can be proved in either order, deferred, or selected later.
second.exact(second.left(h))
first.exact(first.right(h))
theorem = proof.finish()
print(theorem)
print("Axiom dependencies:", len(theorem.axioms()))
if __name__ == "__main__":
main()
Run from the repository root PYTHONPATH=bindings/python:docs/examples/python/library pixi run python docs/examples/python/library/applying_theorems.py
Output
First premise: Q
Second premise: P
⊢ P ∧ Q → Q ∧ P
Axiom dependencies: 0
Rewrite beneath a quantifier through an explicit fresh-variable scope¶
Mojo
"""Rewrite beneath a quantifier through an explicit fresh-variable scope."""
from judgment import Session, forall
def main() raises:
var s = Session()
var A = s.declare_type("A")
var proof = s.theorem("replace_under_forall")
var values = proof.vars("a b", A)
var a, b = values[0], values[1]
var equality = proof.given("equality", a == b)
var x = proof.bound_var("x", A)
proof.goal(forall(x, x == a) == forall(x, x == b))
var opened = proof.lhs().under("z")
_ = opened.body().at(a).rw(equality)
_ = opened.finish()
proof.rfl()
print(proof.finish())
Run from the repository root pixi run core-run docs/examples/library/binder_rewrites.mojo
Output
⊢ ∀a:A. ∀b:A. a = b → (∀x:A. x = a) = (∀x:A. x = b)
Python
"""Rewrite beneath a quantifier through an explicit fresh-variable scope."""
from judgment import Session, forall
def main():
s = Session()
A = s.declare_type("A")
proof = s.theorem("replace_under_forall")
values = proof.vars("a b", A)
a, b = values[0], values[1]
equality = proof.given("equality", a == b)
x = proof.bound_var("x", A)
proof.goal(forall(x, x == a) == forall(x, x == b))
opened = proof.lhs().under("z")
_ = opened.body().at(a).rw(equality)
_ = opened.finish()
proof.rfl()
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/binder_rewrites.py
Output
⊢ ∀a:A. ∀b:A. a = b → (∀x:A. x = a) = (∀x:A. x = b)
Prove a readable chain and discharge a step after writing the calculation¶
Mojo
"""Prove a readable chain and discharge a step after writing the calculation."""
from judgment import Session
def main() raises:
var s = Session()
var A = s.declare_type("A")
var proof = s.theorem("equality_chain")
var values = proof.vars("a b c", A)
var a, b, c = values[0], values[1], values[2]
var ab = proof.given("ab", a == b)
var bc = proof.given("bc", b == c)
proof.goal(a == c)
var chain = proof.calc(a)
chain.eq(b, using=ab, label="ab")
var last = chain.step("last_step", to=c)
last.sorry()
print(chain.format())
var outstanding = chain.obligations()
last = chain.select(outstanding[0])
last.resume()
last.exact(bc)
print(chain.format())
proof.exact(chain.finish())
print(proof.finish())
Run from the repository root pixi run core-run docs/examples/library/calculation_chains.mojo
Output
a
= b [ab: checked]
= c [last_step: deferred]
a
= b [ab: checked]
= c [last_step: solved]
⊢ ∀a:A. ∀b:A. ∀c:A. a = b → b = c → a = c
Python
"""Prove a readable chain and discharge a step after writing the calculation."""
from judgment import Session
def main():
s = Session()
A = s.declare_type("A")
proof = s.theorem("equality_chain")
values = proof.vars("a b c", A)
a, b, c = values[0], values[1], values[2]
ab = proof.given("ab", a == b)
bc = proof.given("bc", b == c)
proof.goal(a == c)
chain = proof.calc(a)
chain.eq(b, using=ab, label="ab")
last = chain.step("last_step", to=c)
last.sorry()
print(chain.format())
outstanding = chain.obligations()
last = chain.select(outstanding[0])
last.resume()
last.exact(bc)
print(chain.format())
proof.exact(chain.finish())
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/calculation_chains.py
Output
a
= b [ab: checked]
= c [last_step: deferred]
a
= b [ab: checked]
= c [last_step: solved]
⊢ ∀a:A. ∀b:A. ∀c:A. a = b → b = c → a = c
Restore an exploratory rewrite and retry at a different occurrence¶
Mojo
"""Restore an exploratory rewrite and retry at a different occurrence."""
from std.testing import assert_true
from judgment import Session, implies
def main() raises:
var s = Session()
var P = s.prop("P")
var Q = s.prop("Q")
var R = s.prop("R")
var start = (P & R) | (P & R)
var wanted = (P & R) | (Q & R)
var statement = implies(P == Q, start == wanted)
var proof = s.theorem("retry_rewrite", statement)
var equal = proof.intro("equal")
var saved = proof.checkpoint()
var t = proof.tactics()
# This checked rewrite succeeds, but reflexivity cannot finish this route.
_ = proof.lhs().at(P, occurrence=1).rw(equal)
var trial = proof.by(t.rfl())
assert_true(trial.status() == "no_match" and not trial.changed())
assert_true(proof.target().same_as(((Q & R) | (P & R)) == wanted))
print("First occurrence:", trial.status())
# Undo the earlier direct rewrite; by only stages its own tactic program.
proof.restore(saved)
assert_true(proof.target().same_as(start == wanted))
print("Restored original goal:", proof.target().same_as(start == wanted))
# Restoration invalidates old foci, so select the occurrence afresh.
_ = proof.lhs().at(P, occurrence=2).rw(equal)
proof.rfl()
var theorem = proof.finish()
assert_true(theorem.statement().same_as(statement))
assert_true(len(theorem.axioms()) == 0 and len(theorem.admissions()) == 0)
print(theorem)
print("Axiom dependencies:", len(theorem.axioms()))
Run from the repository root pixi run core-run docs/examples/library/checkpoint_retry.mojo
Output
First occurrence: no_match
Restored original goal: True
⊢ P = Q → (P ∧ R ∨ P ∧ R) = (P ∧ R ∨ Q ∧ R)
Axiom dependencies: 0
Python
"""Restore an exploratory rewrite and retry at a different occurrence."""
from judgment import Session, implies
def main():
s = Session()
P = s.prop("P")
Q = s.prop("Q")
R = s.prop("R")
start = (P & R) | (P & R)
wanted = (P & R) | (Q & R)
statement = implies(P == Q, start == wanted)
proof = s.theorem("retry_rewrite", statement)
equal = proof.intro("equal")
saved = proof.checkpoint()
t = proof.tactics()
# This checked rewrite succeeds, but reflexivity cannot finish this route.
_ = proof.lhs().at(P, occurrence=1).rw(equal)
trial = proof.by(t.rfl())
assert trial.status() == "no_match" and not trial.changed()
assert proof.target().same_as(((Q & R) | (P & R)) == wanted)
print("First occurrence:", trial.status())
# Undo the earlier direct rewrite; by only stages its own tactic program.
proof.restore(saved)
assert proof.target().same_as(start == wanted)
print("Restored original goal:", proof.target().same_as(start == wanted))
# Restoration invalidates old foci, so select the occurrence afresh.
_ = proof.lhs().at(P, occurrence=2).rw(equal)
proof.rfl()
theorem = proof.finish()
assert theorem.statement().same_as(statement)
assert len(theorem.axioms()) == 0 and len(theorem.admissions()) == 0
print(theorem)
print("Axiom dependencies:", len(theorem.axioms()))
if __name__ == "__main__":
main()
Run from the repository root PYTHONPATH=bindings/python:docs/examples/python/library pixi run python docs/examples/python/library/checkpoint_retry.py
Output
First occurrence: no_match
Restored original goal: True
⊢ P = Q → (P ∧ R ∨ P ∧ R) = (P ∧ R ∨ Q ∧ R)
Axiom dependencies: 0
Swap a disjunction by explicitly choosing what each case proves¶
Mojo
"""Swap a disjunction by explicitly choosing what each case proves."""
from judgment import Session, implies
def main() raises:
var s = Session()
var P = s.prop("P")
var Q = s.prop("Q")
var proof = s.theorem("swap_disjunction", implies(P | Q, Q | P))
var either = proof.intro("either")
_ = proof.cases(either, left_name="hp", right_name="hq")
# In the P case, prove the right side of Q | P.
var p_case = proof.select("left")
p_case.choose_right()
p_case.exact(p_case.fact("hp"))
# In the Q case, prove the left side of Q | P.
var q_case = proof.select("right")
q_case.choose_left()
q_case.exact(q_case.fact("hq"))
var theorem = proof.finish()
print(theorem)
print("Axiom dependencies:", len(theorem.axioms()))
Run from the repository root pixi run core-run docs/examples/library/choosing_disjuncts.mojo
Output
⊢ P ∨ Q → Q ∨ P
Axiom dependencies: 0
Python
"""Swap a disjunction by explicitly choosing what each case proves."""
from judgment import Session, implies
def main():
s = Session()
P = s.prop("P")
Q = s.prop("Q")
proof = s.theorem("swap_disjunction", implies(P | Q, Q | P))
either = proof.intro("either")
_ = proof.cases(either, left_name="hp", right_name="hq")
# In the P case, prove the right side of Q | P.
p_case = proof.select("left")
p_case.choose_right()
p_case.exact(p_case.fact("hp"))
# In the Q case, prove the left side of Q | P.
q_case = proof.select("right")
q_case.choose_left()
q_case.exact(q_case.fact("hq"))
theorem = proof.finish()
print(theorem)
print("Axiom dependencies:", len(theorem.axioms()))
if __name__ == "__main__":
main()
Run from the repository root PYTHONPATH=bindings/python:docs/examples/python/library pixi run python docs/examples/python/library/choosing_disjuncts.py
Output
⊢ P ∨ Q → Q ∨ P
Axiom dependencies: 0
Declare a semigroup class, instances at a type and at list(α) by an instance definition, and use a theorem over a sorted parameter¶
Mojo
"""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
"""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
Use a theorem parameter for a leading universal quantifier¶
Mojo
"""Use a theorem parameter for a leading universal quantifier."""
from judgment import Session, exists
def main() raises:
var s = Session()
var proof = s.theorem("self_witness")
var A = proof.type_var("A")
var x = proof.var("x", A)
var y = proof.bound_var("y", A)
proof.goal(exists(y, y == x))
proof.witness(x)
proof.rfl()
var theorem = proof.finish()
print(theorem)
print("Axiom dependencies:", len(theorem.axioms()))
Run from the repository root pixi run core-run docs/examples/library/compact_quantified_proof.mojo
Output
[A] ⊢ ∀x:A. ∃y:A. y = x
Axiom dependencies: 0
Python
"""Use a theorem parameter for a leading universal quantifier."""
from judgment import Session, exists
def main():
s = Session()
proof = s.theorem("self_witness")
A = proof.type_var("A")
x = proof.var("x", A)
y = proof.bound_var("y", A)
proof.goal(exists(y, y == x))
proof.witness(x)
proof.rfl()
theorem = proof.finish()
print(theorem)
print("Axiom dependencies:", len(theorem.axioms()))
if __name__ == "__main__":
main()
Run from the repository root PYTHONPATH=bindings/python:docs/examples/python/library pixi run python docs/examples/python/library/compact_quantified_proof.py
Output
[A] ⊢ ∀x:A. ∃y:A. y = x
Axiom dependencies: 0
Replace a premise loop with one atomic, explicitly chosen tactic sequence¶
Mojo
"""Replace a premise loop with one atomic, explicitly chosen tactic sequence."""
from judgment import Session, implies
def main() raises:
var s = Session()
var source = s.theorem("join")
var Left = source.prop("Left")
var Right = source.prop("Right")
var left = source.given("left", Left)
var right = source.given("right", Right)
source.goal(Left & Right)
source.exact(source.conjoin(left, right))
var join = source.finish()
var P = s.prop("P")
var Q = s.prop("Q")
var goal = implies(P, implies(Q, P & Q))
# Direct application returns premises for an explicit loop.
var direct = s.theorem("direct", goal)
_ = direct.intro("p")
_ = direct.intro("q")
var premises = direct.apply(join)
for i in range(len(premises)):
premises[i].assumption()
print(direct.finish())
# Composition makes application and every premise proof one atomic attempt.
var proof = s.theorem("composed", goal)
_ = proof.intro("p")
_ = proof.intro("q")
var t = proof.tactics()
var solve = t.apply(join).then(t.assumption()).require_closed()
print("Composed:", proof.by(solve).status())
print(proof.finish())
# The same program cannot prove Q without evidence; even its first premise
# solution rolls back, so the caller retains the complete original goal.
var partial = s.theorem("partial", implies(P, P & Q))
_ = partial.intro("p")
var before = partial.format()
print("Missing premise:", partial.by(solve).status())
print("Draft unchanged:", partial.format() == before)
Run from the repository root pixi run core-run docs/examples/library/composable_application.mojo
Output
⊢ P → Q → P ∧ Q
Composed: solved
⊢ P → Q → P ∧ Q
Missing premise: no_match
Draft unchanged: True
Python
"""Replace a premise loop with one atomic, explicitly chosen tactic sequence."""
from judgment import Session, implies
def main():
s = Session()
source = s.theorem("join")
Left = source.prop("Left")
Right = source.prop("Right")
left = source.given("left", Left)
right = source.given("right", Right)
source.goal(Left & Right)
source.exact(source.conjoin(left, right))
join = source.finish()
P = s.prop("P")
Q = s.prop("Q")
goal = implies(P, implies(Q, P & Q))
# Direct application returns premises for an explicit loop.
direct = s.theorem("direct", goal)
_ = direct.intro("p")
_ = direct.intro("q")
premises = direct.apply(join)
for i in range(len(premises)):
premises[i].assumption()
print(direct.finish())
# Composition makes application and every premise proof one atomic attempt.
proof = s.theorem("composed", goal)
_ = proof.intro("p")
_ = proof.intro("q")
t = proof.tactics()
solve = t.apply(join).then(t.assumption()).require_closed()
print("Composed:", proof.by(solve).status())
print(proof.finish())
# The same program cannot prove Q without evidence; even its first premise
# solution rolls back, so the caller retains the complete original goal.
partial = s.theorem("partial", implies(P, P & Q))
_ = partial.intro("p")
before = partial.format()
print("Missing premise:", partial.by(solve).status())
print("Draft unchanged:", partial.format() == before)
if __name__ == "__main__":
main()
Run from the repository root PYTHONPATH=bindings/python:docs/examples/python/library pixi run python docs/examples/python/library/composable_application.py
Output
⊢ P → Q → P ∧ Q
Composed: solved
⊢ P → Q → P ∧ Q
Missing premise: no_match
Draft unchanged: True
Compose explicit tactics and inspect their outcome¶
Mojo
"""Compose explicit tactics and inspect their outcome."""
from judgment import Session, implies
def main() raises:
var s = Session()
var proof = s.theorem("duplicate")
var P = proof.prop("P")
proof.goal(implies(P, P & P))
var t = proof.tactics()
var report = proof.by(t.intro().then(t.split()).then(t.assumption()).require_closed())
print(report.status())
print(proof.finish())
Run from the repository root pixi run core-run docs/examples/library/composed_tactics.mojo
Output
solved
⊢ ∀P:Prop. P → P ∧ P
Python
"""Compose explicit tactics and inspect their outcome."""
from judgment import Session, implies
def main():
s = Session()
proof = s.theorem("duplicate")
P = proof.prop("P")
proof.goal(implies(P, P & P))
t = proof.tactics()
report = proof.by(t.intro().then(t.split()).then(t.assumption()).require_closed())
print(report.status())
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/composed_tactics.py
Output
solved
⊢ ∀P:Prop. P → P ∧ P
Keep conditional calculation steps and their required evidence explicit¶
Mojo
"""Keep conditional calculation steps and their required evidence explicit."""
from std.testing import assert_equal
from judgment import Session, arrow, forall, implies
def main() raises:
var s = Session()
var proof = s.theorem("cancel_twice")
var A = proof.type_var("A")
var f = proof.var("f", arrow(A, A))
var D = proof.var("D", arrow(A, s.prop_type()))
var t = proof.bound_var("t", A)
var law = proof.given("fix_on_D", forall(t, implies(D(t), f(t) == t)))
var x = proof.var("x", A)
var inside = proof.given("inside", D(f(x)))
var at_x = proof.given("at_x", D(x))
proof.goal(f(f(x)) == x)
var chain = proof.calc(f(f(x)))
# The endpoints and supplied condition determine the rule's arguments.
chain.eq(
f(x),
using=law,
premises=[inside],
label="fix at f(x)",
)
# Apply infers x from the equality and exposes D(x) as a separate goal.
var cancel = chain.step("cancel", to=x)
var premises = cancel.apply(law)
assert_equal(len(premises), 1)
assert_equal(premises[0].target().same_as(D(x)), True)
premises[0].sorry()
print(chain.format())
var remaining = chain.obligations()
assert_equal(len(remaining), 1)
print("Required premise:", remaining[0].target().format())
# Having D(x) in the context does not discharge it automatically.
var domain = chain.select(remaining[0])
domain.resume()
domain.exact(at_x)
assert_equal(len(chain.obligations()), 0)
proof.exact(chain.finish())
var theorem = proof.finish()
assert_equal(len(theorem.axioms()), 0)
assert_equal(len(theorem.admissions()), 0)
print(theorem)
Run from the repository root pixi run core-run docs/examples/library/conditional_calculations.mojo
Output
f(f(x))
= f(x) [fix at f(x): checked]
= x [cancel: deferred]
Required premise: D(x)
[A] ⊢ ∀f:(A → A). ∀D:(A → Prop). (∀t:A. D(t) → f(t) = t) → (∀x:A. D(f(x)) → D(x) → f(f(x)) = x)
Python
"""Keep conditional calculation steps and their required evidence explicit."""
from judgment import Session, arrow, forall, implies
def main():
s = Session()
proof = s.theorem("cancel_twice")
A = proof.type_var("A")
f = proof.var("f", arrow(A, A))
D = proof.var("D", arrow(A, s.prop_type()))
t = proof.bound_var("t", A)
law = proof.given("fix_on_D", forall(t, implies(D(t), f(t) == t)))
x = proof.var("x", A)
inside = proof.given("inside", D(f(x)))
at_x = proof.given("at_x", D(x))
proof.goal(f(f(x)) == x)
chain = proof.calc(f(f(x)))
# The endpoints and supplied condition determine the rule's arguments.
chain.eq(
f(x),
using=law,
premises=[inside],
label="fix at f(x)",
)
# Apply infers x from the equality and exposes D(x) as a separate goal.
cancel = chain.step("cancel", to=x)
premises = cancel.apply(law)
assert len(premises) == 1
assert premises[0].target().same_as(D(x)) == True
premises[0].sorry()
print(chain.format())
remaining = chain.obligations()
assert len(remaining) == 1
print("Required premise:", remaining[0].target().format())
# Having D(x) in the context does not discharge it automatically.
domain = chain.select(remaining[0])
domain.resume()
domain.exact(at_x)
assert len(chain.obligations()) == 0
proof.exact(chain.finish())
theorem = proof.finish()
assert len(theorem.axioms()) == 0
assert len(theorem.admissions()) == 0
print(theorem)
if __name__ == "__main__":
main()
Run from the repository root PYTHONPATH=bindings/python:docs/examples/python/library pixi run python docs/examples/python/library/conditional_calculations.py
Output
f(f(x))
= f(x) [fix at f(x): checked]
= x [cancel: deferred]
Required premise: D(x)
[A] ⊢ ∀f:(A → A). ∀D:(A → Prop). (∀t:A. D(t) → f(t) = t) → (∀x:A. D(f(x)) → D(x) → f(f(x)) = x)
Use partial inverses in nested branches with a shared deferred claim¶
Mojo
"""Use partial inverses in nested branches with a shared deferred claim."""
from std.testing import assert_equal
from judgment_shell import Expr, LibError, Proof, Session, arrow, forall, iff, implies
def cancel_on_domain(mut proof: Proof, inverse_name: String, domain_name: String, image: Expr) raises LibError:
"""Prove the forward implication using both explicit domain conditions."""
var same_image = proof.intro("same_image")
var inverse = proof.fact(inverse_name)
var domain = proof.fact(domain_name)
var in_domain_x = proof.left(domain)
var in_domain_y = proof.right(domain)
_ = proof.lhs().rw(inverse, reverse=True, using=[in_domain_x])
_ = proof.lhs().at(image).rw(same_image)
_ = proof.lhs().rw(inverse, using=[in_domain_y])
proof.rfl()
def main() raises:
var s = Session()
var proof = s.theorem("partial_inverses")
var A = proof.type_var("A")
var B = proof.type_var("B")
var f = proof.var("f", arrow(A, B))
var g = proof.var("g", arrow(B, A))
var h = proof.var("h", arrow(B, A))
var D = proof.var("D", arrow(A, s.prop_type()))
var E = proof.var("E", arrow(A, s.prop_type()))
var t = proof.bound_var("t", A)
_ = proof.given("inverse_on_D", forall(t, implies(D(t), g(f(t)) == t)))
_ = proof.given("inverse_on_E", forall(t, implies(E(t), h(f(t)) == t)))
var x = proof.var("x", A)
var y = proof.var("y", A)
var equivalent = iff(f(x) == f(y), x == y)
proof.goal(implies(D(x) & D(y), equivalent) & implies(E(x) & E(y), equivalent))
# Both backward directions will use this claim. It remains an obligation.
var reverse = proof.have("same_inputs_same_image", implies(x == y, f(x) == f(y)))
reverse.sorry()
_ = proof.split()
var on_d = proof.select("left")
var on_e = proof.select("right")
_ = on_d.intro("in_D")
_ = on_e.intro("in_E")
_ = on_d.split()
_ = on_e.split()
assert_equal(len(proof.obligations()), 5)
for goal in proof.obligations():
print(goal.path(), goal.status(), ":", goal.target().format())
# Complete the right domain first; the left paths remain unchanged.
var forward = proof.select(["right", "forward"])
cancel_on_domain(forward, "inverse_on_E", "in_E", f(x))
var backward = proof.select(["right", "backward"])
backward.exact(backward.fact("same_inputs_same_image"))
forward = proof.select(["left", "forward"])
var selected = forward.current_goal()
assert_equal(selected.target().same_as(implies(f(x) == f(y), x == y)), True)
cancel_on_domain(forward, "inverse_on_D", "in_D", f(x))
backward = proof.select(["left", "backward"])
backward.exact(backward.fact("same_inputs_same_image"))
var remaining = proof.obligations()
assert_equal(len(remaining), 1)
assert_equal(remaining[0].status(), "deferred")
print("Remaining:", remaining[0].name(), "[", remaining[0].status(), "]")
var recovered = proof.select("same_inputs_same_image")
assert_equal(recovered.current_goal().status(), "deferred")
recovered.resume()
var equal_inputs = recovered.intro("equal_inputs")
_ = recovered.lhs().at(x).rw(equal_inputs)
recovered.rfl()
var theorem = proof.finish()
assert_equal(len(theorem.axioms()), 0)
assert_equal(len(theorem.admissions()), 0)
print(theorem)
Run from the repository root pixi run mojo run -I src docs/examples/library/conditional_rewrites.mojo
Output
[claim, same_inputs_same_image] deferred : x = y → f(x) = f(y)
[left, forward] open : f(x) = f(y) → x = y
[left, backward] open : x = y → f(x) = f(y)
[right, forward] open : f(x) = f(y) → x = y
[right, backward] open : x = y → f(x) = f(y)
Remaining: same_inputs_same_image [ deferred ]
[A, B] ⊢ ∀f:(A → B). ∀g:(B → A). ∀h:(B → A). ∀D:(A → Prop). ∀E:(A → Prop). (∀t:A. D(t) → g(f(t)) = t) → (∀t:A. E(t) → h(f(t)) = t) → (∀x:A. ∀y:A. (D(x) ∧ D(y) → (f(x) = f(y) ↔ x = y)) ∧ (E(x) ∧ E(y) → (f(x) = f(y) ↔ x = y)))
Python
"""Use partial inverses in nested branches with a shared deferred claim."""
from judgment import Expr, JudgmentError, Proof, Session, arrow, forall, iff, implies
def cancel_on_domain(proof, inverse_name, domain_name, image):
"""Prove the forward implication using both explicit domain conditions."""
same_image = proof.intro("same_image")
inverse = proof.fact(inverse_name)
domain = proof.fact(domain_name)
in_domain_x = proof.left(domain)
in_domain_y = proof.right(domain)
_ = proof.lhs().rw(inverse, reverse=True, using=[in_domain_x])
_ = proof.lhs().at(image).rw(same_image)
_ = proof.lhs().rw(inverse, using=[in_domain_y])
proof.rfl()
def main():
s = Session()
proof = s.theorem("partial_inverses")
A = proof.type_var("A")
B = proof.type_var("B")
f = proof.var("f", arrow(A, B))
g = proof.var("g", arrow(B, A))
h = proof.var("h", arrow(B, A))
D = proof.var("D", arrow(A, s.prop_type()))
E = proof.var("E", arrow(A, s.prop_type()))
t = proof.bound_var("t", A)
_ = proof.given("inverse_on_D", forall(t, implies(D(t), g(f(t)) == t)))
_ = proof.given("inverse_on_E", forall(t, implies(E(t), h(f(t)) == t)))
x = proof.var("x", A)
y = proof.var("y", A)
equivalent = iff(f(x) == f(y), x == y)
proof.goal(implies(D(x) & D(y), equivalent) & implies(E(x) & E(y), equivalent))
# Both backward directions will use this claim. It remains an obligation.
reverse = proof.have("same_inputs_same_image", implies(x == y, f(x) == f(y)))
reverse.sorry()
_ = proof.split()
on_d = proof.select("left")
on_e = proof.select("right")
_ = on_d.intro("in_D")
_ = on_e.intro("in_E")
_ = on_d.split()
_ = on_e.split()
assert len(proof.obligations()) == 5
for goal in proof.obligations():
print("[" + ", ".join(goal.path()) + "]", goal.status(), ":", goal.target().format())
# Complete the right domain first; the left paths remain unchanged.
forward = proof.select(["right", "forward"])
cancel_on_domain(forward, "inverse_on_E", "in_E", f(x))
backward = proof.select(["right", "backward"])
backward.exact(backward.fact("same_inputs_same_image"))
forward = proof.select(["left", "forward"])
selected = forward.current_goal()
assert selected.target().same_as(implies(f(x) == f(y), x == y)) == True
cancel_on_domain(forward, "inverse_on_D", "in_D", f(x))
backward = proof.select(["left", "backward"])
backward.exact(backward.fact("same_inputs_same_image"))
remaining = proof.obligations()
assert len(remaining) == 1
assert remaining[0].status() == "deferred"
print("Remaining:", remaining[0].name(), "[", remaining[0].status(), "]")
recovered = proof.select("same_inputs_same_image")
assert recovered.current_goal().status() == "deferred"
recovered.resume()
equal_inputs = recovered.intro("equal_inputs")
_ = recovered.lhs().at(x).rw(equal_inputs)
recovered.rfl()
theorem = proof.finish()
assert len(theorem.axioms()) == 0
assert len(theorem.admissions()) == 0
print(theorem)
if __name__ == "__main__":
main()
Run from the repository root PYTHONPATH=bindings/python:docs/examples/python/library pixi run python docs/examples/python/library/conditional_rewrites.py
Output
[claim, same_inputs_same_image] deferred : x = y → f(x) = f(y)
[left, forward] open : f(x) = f(y) → x = y
[left, backward] open : x = y → f(x) = f(y)
[right, forward] open : f(x) = f(y) → x = y
[right, backward] open : x = y → f(x) = f(y)
Remaining: same_inputs_same_image [ deferred ]
[A, B] ⊢ ∀f:(A → B). ∀g:(B → A). ∀h:(B → A). ∀D:(A → Prop). ∀E:(A → Prop). (∀t:A. D(t) → g(f(t)) = t) → (∀t:A. E(t) → h(f(t)) = t) → (∀x:A. ∀y:A. (D(x) ∧ D(y) → (f(x) = f(y) ↔ x = y)) ∧ (E(x) ∧ E(y) → (f(x) = f(y) ↔ x = y)))
Define typed functions and unfold exactly the selected occurrence¶
Mojo
"""Define typed functions and unfold exactly the selected occurrence."""
from judgment import Session, arrow
def main() raises:
var s = Session()
var point = s.declare_type("Point")
var map_ = s.symbol("map", arrow(point, point))
var definition = s.definition("identity", transparent=False)
var A = definition.type_var("A")
var value = definition.var("value", A)
var identity = definition.finish(value)
var id = identity.symbol(type_args=[point])
var proof = s.theorem("nested_identity")
var x = proof.var("x", point)
proof.goal(map_(id(id(x))) == map_(x))
_ = proof.lhs().at(id(id(x))).unfold(identity).unfold(identity)
proof.rfl()
print(proof.finish())
# Opaque definitions still provide checked defining equations.
print(identity.equation())
var P = s.prop("P")
var alias = s.define("Alias", P)
var conversion = s.theorem("alias", alias.symbol() == P)
conversion.change(P == P, unfold=[alias])
conversion.rfl()
print(conversion.finish())
Run from the repository root pixi run core-run docs/examples/library/definitions.mojo
Output
⊢ ∀x:Point. map(identity(identity(x))) = map(x)
[A] ⊢ identity = (λvalue:A. value)
⊢ Alias = P
Python
"""Define typed functions and unfold exactly the selected occurrence."""
from judgment import Session, arrow
def main():
s = Session()
point = s.declare_type("Point")
map_ = s.symbol("map", arrow(point, point))
definition = s.definition("identity", transparent=False)
A = definition.type_var("A")
value = definition.var("value", A)
identity = definition.finish(value)
id = identity.symbol(type_args=[point])
proof = s.theorem("nested_identity")
x = proof.var("x", point)
proof.goal(map_(id(id(x))) == map_(x))
_ = proof.lhs().at(id(id(x))).unfold(identity).unfold(identity)
proof.rfl()
print(proof.finish())
# Opaque definitions still provide checked defining equations.
print(identity.equation())
P = s.prop("P")
alias = s.define("Alias", P)
conversion = s.theorem("alias", alias.symbol() == P)
conversion.change(P == P, unfold=[alias])
conversion.rfl()
print(conversion.finish())
if __name__ == "__main__":
main()
Run from the repository root PYTHONPATH=bindings/python:docs/examples/python/library pixi run python docs/examples/python/library/definitions.py
Output
⊢ ∀x:Point. map(identity(identity(x))) = map(x)
[A] ⊢ identity = (λvalue:A. value)
⊢ Alias = P
Use compact exact literals with an explicitly registered arithmetic profile¶
Mojo
"""Use compact exact literals with an explicitly registered arithmetic profile."""
from judgment import Session
from exact_arithmetic_setup import numeric_setup
def main() raises:
var s = Session()
var setup = numeric_setup(s, "Q", rational=True)
var q = setup.register_rationals("rational_literals")
var half = q.rational(1, 2)
var third = q.rational(1, 3)
var proof = s.theorem("fraction_sum", half + third == q.rational(5, 6))
proof.rfl()
var theorem = proof.finish()
print(theorem)
# Retrieve the same profile by carrier; its large numeral remains one node.
var again = s.arithmetic(setup.kind)
var large = again.number("123456789012345678901234567890")
var arithmetic = s.theorem("large_sum", large + 1 == q.number("123456789012345678901234567891"))
arithmetic.rfl()
print(arithmetic.finish())
print("Reduced fraction:", q.rational(-10, -12).format())
print("Inverse of zero:", q.inverse(q.number(0)).format())
Run from the repository root pixi run mojo run -I src docs/examples/library/exact_arithmetic.mojo
Output
[assuming 16 axioms] ⊢ 1/2 + 1/3 = 5/6
axioms: Q.add_assoc, Q.add_comm, Q.add_zero, Q.mul_assoc, … (+12 more)
[assuming 16 axioms] ⊢ 123456789012345678901234567890 + 1 = 123456789012345678901234567891
axioms: Q.add_assoc, Q.add_comm, Q.add_zero, Q.mul_assoc, … (+12 more)
Reduced fraction: 5/6
Inverse of zero: Q.inv(0)
Python
"""Use compact exact literals with an explicitly registered arithmetic profile."""
from judgment import Session
from exact_arithmetic_setup import numeric_setup
def main():
s = Session()
setup = numeric_setup(s, "Q", rational=True)
q = setup.register_rationals("rational_literals")
half = q.rational(1, 2)
third = q.rational(1, 3)
proof = s.theorem("fraction_sum", half + third == q.rational(5, 6))
proof.rfl()
theorem = proof.finish()
print(theorem)
# Retrieve the same profile by carrier; its large numeral remains one node.
again = s.arithmetic(setup.kind)
large = again.number("123456789012345678901234567890")
arithmetic = s.theorem("large_sum", large + 1 == q.number("123456789012345678901234567891"))
arithmetic.rfl()
print(arithmetic.finish())
print("Reduced fraction:", q.rational(-10, -12).format())
print("Inverse of zero:", q.inverse(q.number(0)).format())
if __name__ == "__main__":
main()
Run from the repository root PYTHONPATH=bindings/python:docs/examples/python/library pixi run python docs/examples/python/library/exact_arithmetic.py
Output
[assuming 16 axioms] ⊢ 1/2 + 1/3 = 5/6
axioms: Q.add_assoc, Q.add_comm, Q.add_zero, Q.mul_assoc, … (+12 more)
[assuming 16 axioms] ⊢ 123456789012345678901234567890 + 1 = 123456789012345678901234567891
axioms: Q.add_assoc, Q.add_comm, Q.add_zero, Q.mul_assoc, … (+12 more)
Reduced fraction: 5/6
Inverse of zero: Q.inv(0)
Separate deferred work from an explicitly labeled mathematical assumption¶
Mojo
"""Separate deferred work from an explicitly labeled mathematical assumption."""
from judgment import Session, implies
def main() raises:
var s = Session()
var P = s.prop("P")
var Q = s.prop("Q")
var proof = s.theorem("conditional", implies(P, Q))
_ = proof.intro("h")
proof.sorry()
print("Deferred obligations:", len(proof.obligations()))
proof.resume()
proof.admit("missing_lemma", "Awaiting the mathematical proof")
var theorem = proof.finish()
print(theorem.format(details=True))
Run from the repository root pixi run core-run docs/examples/library/explicit_admission.mojo
Output
Deferred obligations: 1
[admitted] ⊢ P → Q
Admissions (1):
missing_lemma: P → Q
reason: Awaiting the mathematical proof
Python
"""Separate deferred work from an explicitly labeled mathematical assumption."""
from judgment import Session, implies
def main():
s = Session()
P = s.prop("P")
Q = s.prop("Q")
proof = s.theorem("conditional", implies(P, Q))
_ = proof.intro("h")
proof.sorry()
print("Deferred obligations:", len(proof.obligations()))
proof.resume()
proof.admit("missing_lemma", "Awaiting the mathematical proof")
theorem = proof.finish()
print(theorem.format(details=True))
if __name__ == "__main__":
main()
Run from the repository root PYTHONPATH=bindings/python:docs/examples/python/library pixi run python docs/examples/python/library/explicit_admission.py
Output
Deferred obligations: 1
[admitted] ⊢ P → Q
Admissions (1):
missing_lemma: P → Q
reason: Awaiting the mathematical proof
Prove conjunction commutativity with a small session-owned API¶
Mojo
"""Prove conjunction commutativity with a small session-owned API."""
from std.testing import assert_true
from judgment import Session, implies
def main() raises:
var s = Session()
var P = s.prop("P")
var Q = s.prop("Q")
var target = implies(P & Q, Q & P)
var proof = s.theorem("and_swap", target)
var h = proof.intro("h")
_ = proof.split()
var left = proof.select("left")
left.exact(proof.right(h))
var right = proof.select("right")
right.exact(proof.left(h))
var theorem = proof.finish()
assert_true(theorem.statement().same_as(target))
assert_true(s.fact("and_swap").statement().same_as(target))
print(theorem)
var forward = s.proof()
var premise = forward.assume(P & Q)
var swapped = forward.conjoin(forward.right(premise), forward.left(premise))
var result = forward.finish(swapped)
assert_true(result.statement().same_as(target))
print(result)
Run from the repository root pixi run core-run docs/examples/library/first_proof.mojo
Output
⊢ P ∧ Q → Q ∧ P
⊢ P ∧ Q → Q ∧ P
Python
"""Prove conjunction commutativity with a small session-owned API."""
from judgment import Session, implies
def main():
s = Session()
P = s.prop("P")
Q = s.prop("Q")
target = implies(P & Q, Q & P)
proof = s.theorem("and_swap", target)
h = proof.intro("h")
_ = proof.split()
left = proof.select("left")
left.exact(proof.right(h))
right = proof.select("right")
right.exact(proof.left(h))
theorem = proof.finish()
assert theorem.statement().same_as(target)
assert s.fact("and_swap").statement().same_as(target)
print(theorem)
forward = s.proof()
premise = forward.assume(P & Q)
swapped = forward.conjoin(forward.right(premise), forward.left(premise))
result = forward.finish(swapped)
assert result.statement().same_as(target)
print(result)
if __name__ == "__main__":
main()
Run from the repository root PYTHONPATH=bindings/python:docs/examples/python/library pixi run python docs/examples/python/library/first_proof.py
Output
⊢ P ∧ Q → Q ∧ P
⊢ P ∧ Q → Q ∧ P
Seal a base theory snapshot, then open a new Session over it and import its declarations¶
Mojo
"""Seal a base theory snapshot, then open a new Session over it and import its declarations."""
from judgment import Session, arrow, forall
def main() raises:
# Build a base theory in one session and seal it into an immutable Snapshot.
var base = Session()
var nat = base.declare_type("nat")
var zero = base.symbol("zero", nat)
var succ = base.symbol("succ", arrow(nat, nat))
var n = base.bound_var("n", nat)
_ = base.axiom("succ_ne_zero", forall(n, ~(succ(n) == zero)))
var snapshot = base.seal()
# Open a new session over the snapshot and import the declarations it needs.
var s = Session.open(snapshot)
var N = s.import_type("nat")
var z = s.import_symbol("zero")
var S = s.import_symbol("succ")
var axiom = s.import_fact("succ_ne_zero")
print(axiom)
var proof = s.theorem("one_ne_zero", ~(S(z) == z))
proof.exact(proof.use(axiom, terms=[z]))
var result = proof.finish()
print(result)
print(result.axioms()[0], N.format())
var exported = result.step()
print(len(exported.hypotheses()) == 0)
Run from the repository root pixi run core-run docs/examples/library/imported_theory.mojo
Output
[axiom] ⊢ ∀x·1:nat. ¬(succ(x·1) = zero)
axioms: succ_ne_zero
[assuming 1 axiom] ⊢ ¬(succ(zero) = zero)
axioms: succ_ne_zero
succ_ne_zero nat
True
Python
"""Seal a base theory snapshot, then open a new Session over it and import its declarations."""
from judgment import Session, arrow, forall
def main():
# Build a base theory in one session and seal it into an immutable Snapshot.
base = Session()
nat = base.declare_type("nat")
zero = base.symbol("zero", nat)
succ = base.symbol("succ", arrow(nat, nat))
n = base.bound_var("n", nat)
_ = base.axiom("succ_ne_zero", forall(n, ~(succ(n) == zero)))
snapshot = base.seal()
# Open a new session over the snapshot and import the declarations it needs.
s = Session.open(snapshot)
N = s.import_type("nat")
z = s.import_symbol("zero")
S = s.import_symbol("succ")
axiom = s.import_fact("succ_ne_zero")
print(axiom)
proof = s.theorem("one_ne_zero", ~(S(z) == z))
proof.exact(proof.use(axiom, terms=[z]))
result = proof.finish()
print(result)
print(result.axioms()[0], N.format())
exported = result.step()
print(len(exported.hypotheses()) == 0)
if __name__ == "__main__":
main()
Run from the repository root PYTHONPATH=bindings/python:docs/examples/python/library pixi run python docs/examples/python/library/imported_theory.py
Output
[axiom] ⊢ ∀x·1:nat. ¬(succ(x·1) = zero)
axioms: succ_ne_zero
[assuming 1 axiom] ⊢ ¬(succ(zero) = zero)
axioms: succ_ne_zero
succ_ne_zero nat
True
Inspect a deferred claim and recover it by name or exact goal identity¶
Mojo
"""Inspect a deferred claim and recover it by name or exact goal identity."""
from judgment import Session, implies
def main() raises:
var s = Session()
var P = s.prop("P")
var Q = s.prop("Q")
var proof = s.theorem("swap", implies(P & Q, Q & P))
var h = proof.intro("h")
var step = proof.have("first_component", Q)
step.sorry()
proof.exact(proof.conjoin(step.fact(), proof.left(h)))
print(proof.format())
var goals = proof.obligations()
var missing = proof.select("first_component")
missing.resume()
missing = proof.select(goals[0])
missing.exact(missing.right(missing.fact("h")))
print(proof.format())
print(proof.finish())
print(proof.format())
Run from the repository root pixi run core-run docs/examples/library/inspecting_proofs.mojo
Output
swap: 1 obligation
goal 2 [deferred] first_component [claim / first_component]
h: [local] ⊢ P ∧ Q
⊢ Q
swap: ready to finish
⊢ P ∧ Q → Q ∧ P
swap: finished
Python
"""Inspect a deferred claim and recover it by name or exact goal identity."""
from judgment import Session, implies
def main():
s = Session()
P = s.prop("P")
Q = s.prop("Q")
proof = s.theorem("swap", implies(P & Q, Q & P))
h = proof.intro("h")
step = proof.have("first_component", Q)
step.sorry()
proof.exact(proof.conjoin(step.fact(), proof.left(h)))
print(proof.format())
goals = proof.obligations()
missing = proof.select("first_component")
missing.resume()
missing = proof.select(goals[0])
missing.exact(missing.right(missing.fact("h")))
print(proof.format())
print(proof.finish())
print(proof.format())
if __name__ == "__main__":
main()
Run from the repository root PYTHONPATH=bindings/python:docs/examples/python/library pixi run python docs/examples/python/library/inspecting_proofs.py
Output
swap: 1 obligation
goal 2 [deferred] first_component [claim / first_component]
h: [local] ⊢ P ∧ Q
⊢ Q
swap: ready to finish
⊢ P ∧ Q → Q ∧ P
swap: finished
Develop a named intermediate claim independently of its continuation¶
Mojo
"""Develop a named intermediate claim independently of its continuation."""
from judgment import Session, implies
def main() raises:
var s = Session()
var P = s.prop("P")
var Q = s.prop("Q")
var proof = s.theorem("swap_with_claim", implies(P & Q, Q & P))
var h = proof.intro()
var step = proof.have("first_component", Q)
step.sorry()
proof.exact(proof.conjoin(step.fact(), proof.left(h)))
# The continuation is solved, but the intermediate claim still needs proof.
step.resume()
step.exact(step.right(h))
var theorem = proof.finish()
print(theorem)
print("Axiom dependencies:", len(theorem.axioms()))
Run from the repository root pixi run core-run docs/examples/library/intermediate_claims.mojo
Output
⊢ P ∧ Q → Q ∧ P
Axiom dependencies: 0
Python
"""Develop a named intermediate claim independently of its continuation."""
from judgment import Session, implies
def main():
s = Session()
P = s.prop("P")
Q = s.prop("Q")
proof = s.theorem("swap_with_claim", implies(P & Q, Q & P))
h = proof.intro()
step = proof.have("first_component", Q)
step.sorry()
proof.exact(proof.conjoin(step.fact(), proof.left(h)))
# The continuation is solved, but the intermediate claim still needs proof.
step.resume()
step.exact(step.right(h))
theorem = proof.finish()
print(theorem)
print("Axiom dependencies:", len(theorem.axioms()))
if __name__ == "__main__":
main()
Run from the repository root PYTHONPATH=bindings/python:docs/examples/python/library pixi run python docs/examples/python/library/intermediate_claims.py
Output
⊢ P ∧ Q → Q ∧ P
Axiom dependencies: 0
Name an expression inside a proof, then fold and unfold it explicitly¶
Mojo
"""Name an expression inside a proof, then fold and unfold it explicitly."""
from judgment import Session, arrow
def main() raises:
var s = Session()
var A = s.declare_type("A")
var f = s.symbol("f", arrow(A, A))
var proof = s.theorem("named_expression")
var x = proof.var("x", A)
proof.goal(f(f(x)) == f(f(x)))
var t = proof.define("t", f(x))
_ = proof.lhs().at(f(x)).fold(t)
print(proof.target().format())
_ = proof.lhs().at(t).unfold(t)
proof.rfl()
print(proof.finish())
Run from the repository root pixi run core-run docs/examples/library/local_definitions.mojo
Output
f(t) = f(f(x))
⊢ ∀x:A. f(f(x)) = f(f(x))
Python
"""Name an expression inside a proof, then fold and unfold it explicitly."""
from judgment import Session, arrow
def main():
s = Session()
A = s.declare_type("A")
f = s.symbol("f", arrow(A, A))
proof = s.theorem("named_expression")
x = proof.var("x", A)
proof.goal(f(f(x)) == f(f(x)))
t = proof.define("t", f(x))
_ = proof.lhs().at(f(x)).fold(t)
print(proof.target().format())
_ = proof.lhs().at(t).unfold(t)
proof.rfl()
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/local_definitions.py
Output
f(t) = f(f(x))
⊢ ∀x:A. f(f(x)) = f(f(x))
Prove contraposition and equivalence symmetry with explicit logical steps¶
Mojo
"""Prove contraposition and equivalence symmetry with explicit logical steps."""
from std.testing import assert_equal, assert_true
from judgment import Session, iff, implies
def main() raises:
var s = Session()
var P = s.prop("P")
var Q = s.prop("Q")
var target = implies(implies(P, Q), implies(~Q, ~P))
var proof = s.theorem("contraposition", target)
var pq = proof.intro("pq")
var nq = proof.intro("nq")
var hp = proof.intro("hp")
proof.exact(proof.contradiction(nq, proof.use(pq, using=[hp])))
var theorem = proof.finish()
assert_true(theorem.statement().same_as(target))
assert_equal(len(theorem.axioms()), 0)
print(theorem)
var symmetry = s.theorem("iff_symmetry", implies(iff(P, Q), iff(Q, P)))
var equivalence = symmetry.intro("equivalence")
_ = symmetry.split()
var forward = symmetry.select("forward")
var backward = symmetry.select("backward")
forward.exact(symmetry.right(equivalence))
backward.sorry()
print("Deferred directions:", len(symmetry.obligations()))
backward = symmetry.select("backward")
backward.resume()
backward.exact(symmetry.left(equivalence))
theorem = symmetry.finish()
assert_equal(len(theorem.axioms()), 0)
print(theorem)
Run from the repository root pixi run core-run docs/examples/library/logical_proofs.mojo
Output
⊢ (P → Q) → ¬Q → ¬P
Deferred directions: 1
⊢ (P ↔ Q) → (Q ↔ P)
Python
"""Prove contraposition and equivalence symmetry with explicit logical steps."""
from judgment import Session, iff, implies
def main():
s = Session()
P = s.prop("P")
Q = s.prop("Q")
target = implies(implies(P, Q), implies(~Q, ~P))
proof = s.theorem("contraposition", target)
pq = proof.intro("pq")
nq = proof.intro("nq")
hp = proof.intro("hp")
proof.exact(proof.contradiction(nq, proof.use(pq, using=[hp])))
theorem = proof.finish()
assert theorem.statement().same_as(target)
assert len(theorem.axioms()) == 0
print(theorem)
symmetry = s.theorem("iff_symmetry", implies(iff(P, Q), iff(Q, P)))
equivalence = symmetry.intro("equivalence")
_ = symmetry.split()
forward = symmetry.select("forward")
backward = symmetry.select("backward")
forward.exact(symmetry.right(equivalence))
backward.sorry()
print("Deferred directions:", len(symmetry.obligations()))
backward = symmetry.select("backward")
backward.resume()
backward.exact(symmetry.left(equivalence))
theorem = symmetry.finish()
assert len(theorem.axioms()) == 0
print(theorem)
if __name__ == "__main__":
main()
Run from the repository root PYTHONPATH=bindings/python:docs/examples/python/library pixi run python docs/examples/python/library/logical_proofs.py
Output
⊢ (P → Q) → ¬Q → ¬P
Deferred directions: 1
⊢ (P ↔ Q) → (Q ↔ P)
Select nested branches by stable names and literal path components¶
Mojo
"""Select nested branches by stable names and literal path components."""
from std.testing import assert_equal, assert_true
from judgment_shell import LibErrorKind, Session, implies
def main() raises:
var s = Session()
var P = s.prop("P")
var Q = s.prop("Q")
var target = implies(P & Q, (Q & P) & (P & Q))
var proof = s.theorem("nested_pairs", target)
var pair = proof.intro("pair")
_ = proof.split()
var left = proof.select("left")
var right = proof.select("right")
_ = left.split()
_ = right.split()
# Both halves now contain a left goal. An ambiguous short name is refused.
var ambiguous = False
try:
_ = proof.select("left")
except error:
ambiguous = error.kind == LibErrorKind.SHAPE
assert_true(ambiguous)
print("Ambiguous short name refused:", ambiguous)
var last = proof.select(["right", "right"])
last.sorry()
var part = proof.select(["left", "left"])
part.exact(part.right(pair))
part = proof.select(["left", "right"])
part.exact(part.left(pair))
part = proof.select(["right", "left"])
part.exact(part.left(pair))
var remaining = proof.obligations()[0]
var path = remaining.path()
print("Remaining branch:", path[0], "/", path[1])
last = proof.select(remaining.path())
last.resume()
last.exact(last.right(pair))
var theorem = proof.finish()
assert_true(theorem.statement().same_as(target))
assert_equal(len(theorem.axioms()), 0)
print(theorem)
Run from the repository root pixi run mojo run -I src docs/examples/library/named_goals.mojo
Output
Ambiguous short name refused: True
Remaining branch: right / right
⊢ P ∧ Q → Q ∧ P ∧ (P ∧ Q)
Python
"""Select nested branches by stable names and literal path components."""
from judgment import LibErrorKind, Session, implies, JudgmentError
def main():
s = Session()
P = s.prop("P")
Q = s.prop("Q")
target = implies(P & Q, (Q & P) & (P & Q))
proof = s.theorem("nested_pairs", target)
pair = proof.intro("pair")
_ = proof.split()
left = proof.select("left")
right = proof.select("right")
_ = left.split()
_ = right.split()
# Both halves now contain a left goal. An ambiguous short name is refused.
ambiguous = False
try:
_ = proof.select("left")
except JudgmentError as error:
ambiguous = error.kind == LibErrorKind.SHAPE
assert ambiguous
print("Ambiguous short name refused:", ambiguous)
last = proof.select(["right", "right"])
last.sorry()
part = proof.select(["left", "left"])
part.exact(part.right(pair))
part = proof.select(["left", "right"])
part.exact(part.left(pair))
part = proof.select(["right", "left"])
part.exact(part.left(pair))
remaining = proof.obligations()[0]
path = remaining.path()
print("Remaining branch:", path[0], "/", path[1])
last = proof.select(remaining.path())
last.resume()
last.exact(last.right(pair))
theorem = proof.finish()
assert theorem.statement().same_as(target)
assert len(theorem.axioms()) == 0
print(theorem)
if __name__ == "__main__":
main()
Run from the repository root PYTHONPATH=bindings/python:docs/examples/python/library pixi run python docs/examples/python/library/named_goals.py
Output
Ambiguous short name refused: True
Remaining branch: right / right
⊢ P ∧ Q → Q ∧ P ∧ (P ∧ Q)
Use an existential fact through its scoped witness and checked property¶
Mojo
"""Use an existential fact through its scoped witness and checked property."""
from judgment import Session, arrow, exists, implies
def main() raises:
var s = Session()
var proof = s.theorem("project_exists")
var A = proof.type_var("A")
var P = proof.var("P", arrow(A, s.prop_type()))
var Q = proof.var("Q", arrow(A, s.prop_type()))
var x = proof.bound_var("x", A)
proof.goal(implies(exists(x, P(x) & Q(x)), exists(x, P(x))))
var h = proof.intro()
var (w, hw) = proof.obtain(h, "w")
print("Witness:", w.format())
print("Its property:", hw.statement().format())
proof.witness(w)
proof.exact(proof.left(hw))
var theorem = proof.finish()
print(theorem)
print("Axiom dependencies:", len(theorem.axioms()))
Run from the repository root pixi run core-run docs/examples/library/obtaining_witnesses.mojo
Output
Witness: w
Its property: P(w) ∧ Q(w)
[A] ⊢ ∀P:(A → Prop). ∀Q:(A → Prop). (∃x:A. P(x) ∧ Q(x)) → (∃x:A. P(x))
Axiom dependencies: 0
Python
"""Use an existential fact through its scoped witness and checked property."""
from judgment import Session, arrow, exists, implies
def main():
s = Session()
proof = s.theorem("project_exists")
A = proof.type_var("A")
P = proof.var("P", arrow(A, s.prop_type()))
Q = proof.var("Q", arrow(A, s.prop_type()))
x = proof.bound_var("x", A)
proof.goal(implies(exists(x, P(x) & Q(x)), exists(x, P(x))))
h = proof.intro()
w, hw = proof.obtain(h, "w")
print("Witness:", w.format())
print("Its property:", hw.statement().format())
proof.witness(w)
proof.exact(proof.left(hw))
theorem = proof.finish()
print(theorem)
print("Axiom dependencies:", len(theorem.axioms()))
if __name__ == "__main__":
main()
Run from the repository root PYTHONPATH=bindings/python:docs/examples/python/library pixi run python docs/examples/python/library/obtaining_witnesses.py
Output
Witness: w
Its property: P(w) ∧ Q(w)
[A] ⊢ ∀P:(A → Prop). ∀Q:(A → Prop). (∃x:A. P(x) ∧ Q(x)) → (∃x:A. P(x))
Axiom dependencies: 0
Mix direct evidence with named proof holes¶
Mojo
"""Mix direct evidence with named proof holes."""
from judgment import Session, hole, implies, recipe
def main() raises:
var s = Session()
var proof = s.theorem("and_swap")
var parameters = proof.props("P Q")
var P, Q = parameters[0], parameters[1]
proof.goal(implies(P & Q, Q & P))
var h = proof.intro()
var holes = proof.refine(recipe(proof.right(h)).conjoin(hole("prove_P", P)))
var missing = holes["prove_P"]
missing.exact(proof.left(h))
print(proof.finish())
Run from the repository root pixi run core-run docs/examples/library/partial_recipes.mojo
Output
⊢ ∀P:Prop. ∀Q:Prop. P ∧ Q → Q ∧ P
Python
"""Mix direct evidence with named proof holes."""
from judgment import Session, hole, implies, recipe
def main():
s = Session()
proof = s.theorem("and_swap")
parameters = proof.props("P Q")
P, Q = parameters[0], parameters[1]
proof.goal(implies(P & Q, Q & P))
h = proof.intro()
holes = proof.refine(recipe(proof.right(h)).conjoin(hole("prove_P", P)))
missing = holes["prove_P"]
missing.exact(proof.left(h))
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/partial_recipes.py
Output
⊢ ∀P:Prop. ∀Q:Prop. P ∧ Q → Q ∧ P
Prove a common consequence in two independently scoped cases¶
Mojo
"""Prove a common consequence in two independently scoped cases."""
from judgment import Session, implies
def main() raises:
var s = Session()
var P = s.prop("P")
var Q = s.prop("Q")
var R = s.prop("R")
var proof = s.theorem("common_consequence")
var either = proof.given("either", P | Q)
var from_p = proof.given("from_p", implies(P, R))
var from_q = proof.given("from_q", implies(Q, R))
proof.goal(R)
_ = proof.cases(either, left_name="hp", right_name="hq")
var p_case = proof.select("left")
_ = p_case.apply(from_p, using=[p_case.fact("hp")])
var q_case = proof.select("right")
_ = q_case.apply(from_q, using=[q_case.fact("hq")])
var theorem = proof.finish()
print(theorem)
print("Axiom dependencies:", len(theorem.axioms()))
Run from the repository root pixi run core-run docs/examples/library/proof_by_cases.mojo
Output
⊢ P ∨ Q → (P → R) → (Q → R) → R
Axiom dependencies: 0
Python
"""Prove a common consequence in two independently scoped cases."""
from judgment import Session, implies
def main():
s = Session()
P = s.prop("P")
Q = s.prop("Q")
R = s.prop("R")
proof = s.theorem("common_consequence")
either = proof.given("either", P | Q)
from_p = proof.given("from_p", implies(P, R))
from_q = proof.given("from_q", implies(Q, R))
proof.goal(R)
_ = proof.cases(either, left_name="hp", right_name="hq")
p_case = proof.select("left")
_ = p_case.apply(from_p, using=[p_case.fact("hp")])
q_case = proof.select("right")
_ = q_case.apply(from_q, using=[q_case.fact("hq")])
theorem = proof.finish()
print(theorem)
print("Axiom dependencies:", len(theorem.axioms()))
if __name__ == "__main__":
main()
Run from the repository root PYTHONPATH=bindings/python:docs/examples/python/library pixi run python docs/examples/python/library/proof_by_cases.py
Output
⊢ P ∨ Q → (P → R) → (Q → R) → R
Axiom dependencies: 0
State quantified goals, introduce arbitrary variables, and supply witnesses¶
Mojo
"""State quantified goals, introduce arbitrary variables, and supply witnesses."""
from judgment import Session, exists, forall
def main() raises:
var s = Session()
var proof = s.theorem("self_witness")
var A = proof.type_var("A")
var x = proof.bound_var("x", A)
var y = proof.bound_var("y", A)
proof.goal(forall(x, exists(y, y == x)))
var a = proof.intro_var("a")
proof.witness(a)
print("Remaining goal:", proof.target().format())
proof.rfl()
var theorem = proof.finish()
print(theorem)
print("Axiom dependencies:", len(theorem.axioms()))
var Point = s.declare_type("Point")
var origin = s.symbol("origin", Point)
var concrete = s.proof()
print(concrete.finish(concrete.use(theorem, type_args=[Point], terms=[origin])))
Run from the repository root pixi run core-run docs/examples/library/quantified_proof.mojo
Output
Remaining goal: a = a
[A] ⊢ ∀x:A. ∃y:A. y = x
Axiom dependencies: 0
⊢ ∃y:Point. y = origin
Python
"""State quantified goals, introduce arbitrary variables, and supply witnesses."""
from judgment import Session, exists, forall
def main():
s = Session()
proof = s.theorem("self_witness")
A = proof.type_var("A")
x = proof.bound_var("x", A)
y = proof.bound_var("y", A)
proof.goal(forall(x, exists(y, y == x)))
a = proof.intro_var("a")
proof.witness(a)
print("Remaining goal:", proof.target().format())
proof.rfl()
theorem = proof.finish()
print(theorem)
print("Axiom dependencies:", len(theorem.axioms()))
Point = s.declare_type("Point")
origin = s.symbol("origin", Point)
concrete = s.proof()
print(concrete.finish(concrete.use(theorem, type_args=[Point], terms=[origin])))
if __name__ == "__main__":
main()
Run from the repository root PYTHONPATH=bindings/python:docs/examples/python/library pixi run python docs/examples/python/library/quantified_proof.py
Output
Remaining goal: a = a
[A] ⊢ ∀x:A. ∃y:A. y = x
Axiom dependencies: 0
⊢ ∃y:Point. y = origin
Open quantifiers and cases with one tactic, then finish each branch directly; name nested binders freshly¶
Mojo
"""Open quantifiers and cases with one tactic, then finish each branch directly; name nested binders freshly."""
from judgment import Session, arrow, exists, forall, implies
def main() raises:
var s = Session()
var proof = s.theorem("exists_or_split")
var A = proof.type_var("A")
var F = proof.var("F", arrow(A, s.prop_type()))
var G = proof.var("G", arrow(A, s.prop_type()))
var x = proof.bound_var("x", A)
proof.goal(implies(exists(x, F(x) | G(x)), exists(x, F(x)) | exists(x, G(x))))
var t = proof.tactics()
# Each step uses the names the earlier steps gave.
var opening = t.intro("h").then(t.obtain("h", "w", "hw")).then(t.cases("hw", "hf", "hg"))
print(proof.by(opening).status())
# The handle selects the left branch; direct steps find the witness and premises by name.
proof.choose_left()
proof.witness(proof.variable("w"))
proof.exact(proof.fact("hf"))
var right = proof.select("right")
print(right.by(t.choose_right().then(t.witness("w")).then(t.exact("hg"))).status())
print(proof.finish())
# fresh=True picks x, x_1, x_2, ... so one repeated step opens nested universals.
var nested = s.theorem("nested_fresh")
var B = nested.type_var("B")
var R = nested.var("R", arrow(B, s.prop_type()))
var a = nested.bound_var("a", B)
var b = nested.bound_var("b", B)
nested.goal(forall(a, forall(b, implies(R(a), R(a) | R(b)))))
t = nested.tactics()
print(nested.by(t.intro_var("x", fresh=True).repeat().then(t.intro("h"))).status())
print(nested.target().format())
nested.choose_left()
nested.exact(nested.fact("h"))
print(nested.finish())
Run from the repository root pixi run core-run docs/examples/library/quantifier_tactics.mojo
Output
progress
solved
[A] ⊢ ∀F:(A → Prop). ∀G:(A → Prop). (∃x:A. F(x) ∨ G(x)) → (∃x:A. F(x)) ∨ (∃x:A. G(x))
progress
R(x) ∨ R(x_1)
[B] ⊢ ∀R:(B → Prop). ∀a:B. ∀b:B. R(a) → R(a) ∨ R(b)
Python
"""Open quantifiers and cases with one tactic, then finish each branch directly; name nested binders freshly."""
from judgment import Session, arrow, exists, forall, implies
def main():
s = Session()
proof = s.theorem("exists_or_split")
A = proof.type_var("A")
F = proof.var("F", arrow(A, s.prop_type()))
G = proof.var("G", arrow(A, s.prop_type()))
x = proof.bound_var("x", A)
proof.goal(implies(exists(x, F(x) | G(x)), exists(x, F(x)) | exists(x, G(x))))
t = proof.tactics()
# Each step uses the names the earlier steps gave.
opening = t.intro("h").then(t.obtain("h", "w", "hw")).then(t.cases("hw", "hf", "hg"))
print(proof.by(opening).status())
# The handle selects the left branch; direct steps find the witness and premises by name.
proof.choose_left()
proof.witness(proof.variable("w"))
proof.exact(proof.fact("hf"))
right = proof.select("right")
print(right.by(t.choose_right().then(t.witness("w")).then(t.exact("hg"))).status())
print(proof.finish())
# fresh=True picks x, x_1, x_2, ... so one repeated step opens nested universals.
nested = s.theorem("nested_fresh")
B = nested.type_var("B")
R = nested.var("R", arrow(B, s.prop_type()))
a = nested.bound_var("a", B)
b = nested.bound_var("b", B)
nested.goal(forall(a, forall(b, implies(R(a), R(a) | R(b)))))
t = nested.tactics()
print(nested.by(t.intro_var("x", fresh=True).repeat().then(t.intro("h"))).status())
print(nested.target().format())
nested.choose_left()
nested.exact(nested.fact("h"))
print(nested.finish())
if __name__ == "__main__":
main()
Run from the repository root PYTHONPATH=bindings/python:docs/examples/python/library pixi run python docs/examples/python/library/quantifier_tactics.py
Output
progress
solved
[A] ⊢ ∀F:(A → Prop). ∀G:(A → Prop). (∃x:A. F(x) ∨ G(x)) → (∃x:A. F(x)) ∨ (∃x:A. G(x))
progress
R(x) ∨ R(x_1)
[B] ⊢ ∀R:(B → Prop). ∀a:B. ∀b:B. R(a) → R(a) ∨ R(b)
Prove an equality by stating each intermediate expression and its reason¶
Mojo
"""Prove an equality by stating each intermediate expression and its reason."""
from judgment import Session
def main() raises:
var s = Session()
var proof = s.theorem("transitivity")
var A = proof.type_var("A")
var values = proof.vars("a b c", A)
var a, b, c = values[0], values[1], values[2]
var ab = proof.given("ab", a == b)
var bc = proof.given("bc", b == c)
proof.goal(a == c)
var chain = proof.calc(a)
chain.eq(b, using=ab, label="ab")
chain.eq(c, using=bc, label="bc")
print(chain.format())
proof.exact(chain.finish())
print(proof.finish())
Run from the repository root pixi run core-run docs/examples/library/quick_start_calculation.mojo
Output
a
= b [ab: checked]
= c [bc: checked]
[A] ⊢ ∀a:A. ∀b:A. ∀c:A. a = b → b = c → a = c
Python
"""Prove an equality by stating each intermediate expression and its reason."""
from judgment import Session
def main():
s = Session()
proof = s.theorem("transitivity")
A = proof.type_var("A")
values = proof.vars("a b c", A)
a, b, c = values[0], values[1], values[2]
ab = proof.given("ab", a == b)
bc = proof.given("bc", b == c)
proof.goal(a == c)
chain = proof.calc(a)
chain.eq(b, using=ab, label="ab")
chain.eq(c, using=bc, label="bc")
print(chain.format())
proof.exact(chain.finish())
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/quick_start_calculation.py
Output
a
= b [ab: checked]
= c [bc: checked]
[A] ⊢ ∀a:A. ∀b:A. ∀c:A. a = b → b = c → a = c
Complete a goal-first proof by composing checked facts directly¶
Mojo
"""Complete a goal-first proof by composing checked facts directly."""
from judgment import Session, implies
def main() raises:
var s = Session()
var P = s.prop("P")
var Q = s.prop("Q")
var proof = s.theorem("swap", implies(P & Q, Q & P))
var h = proof.intro("h")
proof.exact(proof.conjoin(proof.right(h), proof.left(h)))
var theorem = proof.finish()
print(theorem)
Run from the repository root pixi run core-run docs/examples/library/quick_start_goal.mojo
Output
⊢ P ∧ Q → Q ∧ P
Python
"""Complete a goal-first proof by composing checked facts directly."""
from judgment import Session, implies
def main():
s = Session()
P = s.prop("P")
Q = s.prop("Q")
proof = s.theorem("swap", implies(P & Q, Q & P))
h = proof.intro("h")
proof.exact(proof.conjoin(proof.right(h), proof.left(h)))
theorem = proof.finish()
print(theorem)
if __name__ == "__main__":
main()
Run from the repository root PYTHONPATH=bindings/python:docs/examples/python/library pixi run python docs/examples/python/library/quick_start_goal.py
Output
⊢ P ∧ Q → Q ∧ P
Prove a generic theorem once, then use it for a targeted rewrite¶
Mojo
"""Prove a generic theorem once, then use it for a targeted rewrite."""
from std.testing import assert_true
from judgment import Session, arrow
def main() raises:
var s = Session()
var point = s.declare_type("Point")
var map_ = s.symbol("map", arrow(point, point))
var source = s.theorem("congruence")
var A = source.type_var("A")
var a = source.var("a", A)
var b = source.var("b", A)
var f = source.var("f", arrow(A, A))
var h = source.given("h", a == b)
source.goal(f(a) == f(b))
_ = source.lhs().at(a).rw(h)
source.rfl()
_ = source.finish()
var proof = s.theorem("map_twice")
var x = proof.var("x", point)
var y = proof.var("y", point)
var equal = proof.given("equal", x == y)
proof.goal(map_(map_(x)) == map_(map_(y)))
_ = proof.lhs().at(map_(x)).rw(s.fact("congruence"), using=[equal])
proof.rfl()
var theorem = proof.finish()
assert_true(theorem.statement().format() == "∀x:Point. ∀y:Point. x = y → map(map(x)) = map(map(y))")
print(theorem)
Run from the repository root pixi run core-run docs/examples/library/reusing_theorems.mojo
Output
⊢ ∀x:Point. ∀y:Point. x = y → map(map(x)) = map(map(y))
Python
"""Prove a generic theorem once, then use it for a targeted rewrite."""
from judgment import Session, arrow
def main():
s = Session()
point = s.declare_type("Point")
map_ = s.symbol("map", arrow(point, point))
source = s.theorem("congruence")
A = source.type_var("A")
a = source.var("a", A)
b = source.var("b", A)
f = source.var("f", arrow(A, A))
h = source.given("h", a == b)
source.goal(f(a) == f(b))
_ = source.lhs().at(a).rw(h)
source.rfl()
_ = source.finish()
proof = s.theorem("map_twice")
x = proof.var("x", point)
y = proof.var("y", point)
equal = proof.given("equal", x == y)
proof.goal(map_(map_(x)) == map_(map_(y)))
_ = proof.lhs().at(map_(x)).rw(s.fact("congruence"), using=[equal])
proof.rfl()
theorem = proof.finish()
assert theorem.statement().format() == "∀x:Point. ∀y:Point. x = y → map(map(x)) = map(map(y))"
print(theorem)
if __name__ == "__main__":
main()
Run from the repository root PYTHONPATH=bindings/python:docs/examples/python/library pixi run python docs/examples/python/library/reusing_theorems.py
Output
⊢ ∀x:Point. ∀y:Point. x = y → map(map(x)) = map(map(y))
Specify constants by a theorem, and define an overloaded constant at two types¶
Mojo
"""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
"""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
Construct a subset type from a proved nonemptiness witness¶
Mojo
"""Construct a subset type from a proved nonemptiness witness."""
from judgment import Session, exists, lambda_
def main() raises:
var s = Session()
var A = s.declare_type("A")
var a = s.symbol("a", A)
var witness = s.theorem("nonempty")
var x = witness.bound_var("x", A)
var predicate = lambda_(x, x == a)
witness.goal(exists(x, x == a))
witness.witness(a)
witness.rfl()
var singleton = s.subset("Singleton", predicate, witness.finish())
var proof = s.theorem("round_trip")
var value = proof.var("value", singleton.kind())
proof.goal(singleton.abstract(singleton.represent(value)) == value)
_ = proof.apply(singleton.abs_rep())
print(proof.finish())
Run from the repository root pixi run core-run docs/examples/library/subset_types.mojo
Output
⊢ ∀value:Singleton. Singleton_abs(Singleton_rep(value)) = value
Python
"""Construct a subset type from a proved nonemptiness witness."""
from judgment import Session, exists, lambda_
def main():
s = Session()
A = s.declare_type("A")
a = s.symbol("a", A)
witness = s.theorem("nonempty")
x = witness.bound_var("x", A)
predicate = lambda_(x, x == a)
witness.goal(exists(x, x == a))
witness.witness(a)
witness.rfl()
singleton = s.subset("Singleton", predicate, witness.finish())
proof = s.theorem("round_trip")
value = proof.var("value", singleton.kind())
proof.goal(singleton.abstract(singleton.represent(value)) == value)
_ = proof.apply(singleton.abs_rep())
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/subset_types.py
Output
⊢ ∀value:Singleton. Singleton_abs(Singleton_rep(value)) = value
Describe a goal as data, propose two candidate programs, try both, and commit the one that solves¶
Mojo
"""Describe a goal as data, propose two candidate programs, try both, and commit the one that solves."""
from judgment import Candidate, ExprData, Session, TacticData, TypeData, arrow, exists, implies
def main() raises:
var s = Session()
var T = s.declare_type("T")
var R = s.symbol("R", arrow(T, s.prop_type()))
var proof = s.theorem("witnessed")
var a = proof.var("a", T)
_ = proof.given("ra", R(a))
var y = proof.bound_var("y", T)
proof.goal(exists(y, R(y)))
# A producer sees only data: the goal's path, revision, target, and context.
var goal = proof.current_goal().data()
print(goal.target().format(), goal.variables()[0], goal.premises()[0])
# Two candidate programs, built without any session reference.
var first = TacticData.split().then(TacticData.assumption())
var second = TacticData.witness(ExprData.name("a")).then(TacticData.exact("ra"))
var candidates = [Candidate(goal.path(), goal.revision(), first), Candidate(goal.path(), goal.revision(), second)]
# Trials report without changing the draft; the first that solves is committed.
for candidate in candidates:
var report = proof.trial(proof.compile(candidate.tactic()))
print(report.status())
if report.status() == "solved":
print(proof.by(candidate).status())
break
print(proof.finish())
Run from the repository root pixi run core-run docs/examples/library/tactic_data.mojo
Output
∃y:T. R(y) a ra
no_match
solved
solved
⊢ ∀a:T. R(a) → (∃y:T. R(y))
Python
"""Describe a goal as data, propose two candidate programs, try both, and commit the one that solves."""
from judgment import Candidate, ExprData, Session, TacticData, TypeData, arrow, exists, implies
def main():
s = Session()
T = s.declare_type("T")
R = s.symbol("R", arrow(T, s.prop_type()))
proof = s.theorem("witnessed")
a = proof.var("a", T)
_ = proof.given("ra", R(a))
y = proof.bound_var("y", T)
proof.goal(exists(y, R(y)))
# A producer sees only data: the goal's path, revision, target, and context.
goal = proof.current_goal().data()
print(goal.target().format(), goal.variables()[0], goal.premises()[0])
# Two candidate programs, built without any session reference.
first = TacticData.split().then(TacticData.assumption())
second = TacticData.witness(ExprData.name("a")).then(TacticData.exact("ra"))
candidates = [Candidate(goal.path(), goal.revision(), first), Candidate(goal.path(), goal.revision(), second)]
# Trials report without changing the draft; the first that solves is committed.
for candidate in candidates:
report = proof.trial(proof.compile(candidate.tactic()))
print(report.status())
if report.status() == "solved":
print(proof.by(candidate).status())
break
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/tactic_data.py
Output
∃y:T. R(y) a ra
no_match
solved
solved
⊢ ∀a:T. R(a) → (∃y:T. R(y))
Rewrite one occurrence in a nested expression using explicit evidence¶
Mojo
"""Rewrite one occurrence in a nested expression using explicit evidence."""
from std.testing import assert_true
from judgment import Session, implies
def main() raises:
var s = Session()
var P = s.prop("P")
var Q = s.prop("Q")
var R = s.prop("R")
var before = (~P & R) | (~P & R)
var after = (~P & R) | (~Q & R)
var target = implies(P == Q, before == after)
var proof = s.theorem("rewrite_second", target)
var h = proof.intro("h")
_ = proof.lhs().at(P, occurrence=2).to(Q, using=h)
proof.rfl()
var theorem = proof.finish()
assert_true(theorem.statement().same_as(target))
print(theorem)
Run from the repository root pixi run core-run docs/examples/library/targeted_rewrite.mojo
Output
⊢ P = Q → (¬P ∧ R ∨ ¬P ∧ R) = (¬P ∧ R ∨ ¬Q ∧ R)
Python
"""Rewrite one occurrence in a nested expression using explicit evidence."""
from judgment import Session, implies
def main():
s = Session()
P = s.prop("P")
Q = s.prop("Q")
R = s.prop("R")
before = (~P & R) | (~P & R)
after = (~P & R) | (~Q & R)
target = implies(P == Q, before == after)
proof = s.theorem("rewrite_second", target)
h = proof.intro("h")
_ = proof.lhs().at(P, occurrence=2).to(Q, using=h)
proof.rfl()
theorem = proof.finish()
assert theorem.statement().same_as(target)
print(theorem)
if __name__ == "__main__":
main()
Run from the repository root PYTHONPATH=bindings/python:docs/examples/python/library pixi run python docs/examples/python/library/targeted_rewrite.py
Output
⊢ P = Q → (¬P ∧ R ∨ ¬P ∧ R) = (¬P ∧ R ∨ ¬Q ∧ R)
Inspect a theorem application before selecting it¶
Mojo
"""Inspect a theorem application before selecting it."""
from judgment import Session
def main() raises:
var s = Session()
var identity = s.theorem("identity_refl")
var A = identity.type_var("A")
var x = identity.var("x", A)
identity.goal(x == x)
identity.rfl()
_ = identity.finish()
var P = s.prop("P")
var proof = s.theorem("discovered", P == P)
var candidates = proof.suggest("identity")
print("Candidate:", candidates[0].name())
print("Remaining premises:", len(candidates[0].premises()))
_ = proof.apply(candidates[0])
print(proof.finish())
Run from the repository root pixi run core-run docs/examples/library/theorem_discovery.mojo
Output
Candidate: identity_refl
Remaining premises: 0
⊢ P = P
Python
"""Inspect a theorem application before selecting it."""
from judgment import Session
def main():
s = Session()
identity = s.theorem("identity_refl")
A = identity.type_var("A")
x = identity.var("x", A)
identity.goal(x == x)
identity.rfl()
_ = identity.finish()
P = s.prop("P")
proof = s.theorem("discovered", P == P)
candidates = proof.suggest("identity")
print("Candidate:", candidates[0].name())
print("Remaining premises:", len(candidates[0].premises()))
_ = proof.apply(candidates[0])
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/theorem_discovery.py
Output
Candidate: identity_refl
Remaining premises: 0
⊢ P = P
Retain replacement results and discard temporary work explicitly¶
Mojo
"""Retain replacement results and discard temporary work explicitly."""
from judgment import Session
def main() raises:
var s = Session()
var scope = s.transaction()
var P = s.prop("P")
var proof = s.theorem("reflexivity", P == P)
proof.rfl()
var kept = scope.commit(expressions=[P], facts=[proof.finish()])
var live_P = kept.expressions()[0]
var reused = s.theorem("reused", live_P == live_P)
reused.exact(kept.facts()[0])
print(reused.finish())
var temporary = s.transaction()
_ = s.prop("temporary")
temporary.discard()
print("Registered theorems:", len(s.find()))
Run from the repository root pixi run core-run docs/examples/library/transactions.mojo
Output
⊢ P = P
Registered theorems: 2
Python
"""Retain replacement results and discard temporary work explicitly."""
from judgment import Session
def main():
s = Session()
scope = s.transaction()
P = s.prop("P")
proof = s.theorem("reflexivity", P == P)
proof.rfl()
kept = scope.commit(expressions=[P], facts=[proof.finish()])
live_P = kept.expressions()[0]
reused = s.theorem("reused", live_P == live_P)
reused.exact(kept.facts()[0])
print(reused.finish())
temporary = s.transaction()
_ = s.prop("temporary")
temporary.discard()
print("Registered theorems:", len(s.find()))
if __name__ == "__main__":
main()
Run from the repository root PYTHONPATH=bindings/python:docs/examples/python/library pixi run python docs/examples/python/library/transactions.py
Output
⊢ P = P
Registered theorems: 2
State a generic theorem with typed parameters and rewrite an argument¶
Mojo
"""State a generic theorem with typed parameters and rewrite an argument."""
from std.testing import assert_true
from judgment import Session, arrow
def main() raises:
var s = Session()
var proof = s.theorem("congruence")
var A = proof.type_var("A")
var a = proof.var("a", A)
var b = proof.var("b", A)
var f = proof.var("f", arrow(A, A))
var h = proof.given("h", a == b)
proof.goal(f(a) == f(b))
_ = proof.lhs().at(a).rw(h)
proof.rfl()
var theorem = proof.finish()
assert_true(theorem.type_params()[0].same_as(A))
assert_true(theorem.statement().format() == "∀a:A. ∀b:A. ∀f:(A → A). a = b → f(a) = f(b)")
print(theorem)
Run from the repository root pixi run core-run docs/examples/library/typed_proof.mojo
Output
[A] ⊢ ∀a:A. ∀b:A. ∀f:(A → A). a = b → f(a) = f(b)
Python
"""State a generic theorem with typed parameters and rewrite an argument."""
from judgment import Session, arrow
def main():
s = Session()
proof = s.theorem("congruence")
A = proof.type_var("A")
a = proof.var("a", A)
b = proof.var("b", A)
f = proof.var("f", arrow(A, A))
h = proof.given("h", a == b)
proof.goal(f(a) == f(b))
_ = proof.lhs().at(a).rw(h)
proof.rfl()
theorem = proof.finish()
assert theorem.type_params()[0].same_as(A)
assert theorem.statement().format() == "∀a:A. ∀b:A. ∀f:(A → A). a = b → f(a) = f(b)"
print(theorem)
if __name__ == "__main__":
main()
Run from the repository root PYTHONPATH=bindings/python:docs/examples/python/library pixi run python docs/examples/python/library/typed_proof.py
Output
[A] ⊢ ∀a:A. ∀b:A. ∀f:(A → A). a = b → f(a) = f(b)
Compute literal polynomials while retaining their declared laws¶
Mojo
"""Compute literal polynomials while retaining their declared mathematical laws."""
from apn_mojo import Rational
from judgment import Session
from polynomial_setup import polynomial_setup
def main() raises:
var s = Session()
var setup = polynomial_setup(s)
var p = setup.register_polynomials("polynomials")
var x = p.indeterminate()
var expected = p.polynomial([Rational(-1), Rational(0), Rational(1)])
var proof = s.theorem("difference_of_squares", (x + 1) * (x - 1) == expected)
proof.rfl()
var theorem = proof.finish()
print(theorem)
Run from the repository root pixi run mojo run -I src docs/examples/library/polynomial_arithmetic.mojo
Output
[assuming 28 axioms] ⊢ (1*X[0] + 1) * (1*X[0] - 1) = -1 + 1*X[0]^2
axioms: Q.add_assoc, Q.add_comm, Q.add_zero, Q.mul_assoc, … (+24 more)
Python
"""Compute literal polynomials while retaining their declared mathematical laws."""
from judgment import Session
from polynomial_setup import polynomial_setup
def main():
s = Session()
setup = polynomial_setup(s)
p = setup.register_polynomials("polynomials")
x = p.indeterminate()
expected = p.polynomial([-1, 0, 1])
proof = s.theorem("difference_of_squares", (x + 1) * (x - 1) == expected)
proof.rfl()
theorem = proof.finish()
print(theorem)
main()
Run from the repository root PYTHONPATH=bindings/python:docs/examples/python/library pixi run python docs/examples/python/library/polynomial_arithmetic.py
Output
[assuming 28 axioms] ⊢ (1*X[0] + 1) * (1*X[0] - 1) = -1 + 1*X[0]^2
axioms: Q.add_assoc, Q.add_comm, Q.add_zero, Q.mul_assoc, … (+24 more)
Share one explicitly assumed rational base between two polynomial carriers¶
Mojo
"""Two polynomial carriers share one explicitly assumed rational base."""
from apn_mojo import Rational
from std.testing import assert_equal, assert_true
from judgment_shell import LibErrorKind, Session
from exact_arithmetic_setup import numeric_setup
from polynomial_setup import polynomial_setup
def main() raises:
var s = Session()
var q = numeric_setup(s, "Q", rational=True)
_ = q.register_rationals("rationals")
var first = polynomial_setup(s, base_kind=q.kind, carrier_name="First", prefix="A")
var a = first.register_polynomials("A.literals")
var x = a.indeterminate()
var first_proof = s.theorem("A.difference_of_squares",
(x + 1) * (x - 1) == a.polynomial([Rational(-1), Rational(0), Rational(1)]))
first_proof.rfl()
var first_fact = first_proof.finish()
assert_equal(len(first_fact.axioms()), 28)
assert_equal(len(first_fact.admissions()), 0)
print("First carrier:")
print(first_fact)
var second = polynomial_setup(s, base_kind=q.kind, carrier_name="Second", prefix="B")
var b = second.register_polynomials("B.literals")
var y = b.indeterminate()
var second_proof = s.theorem("B.difference_of_squares",
(y + 1) * (y - 1) == b.polynomial([Rational(-1), Rational(0), Rational(1)]))
second_proof.rfl()
var second_fact = second_proof.finish()
# Its later canonical signature includes both polynomial registrations.
assert_equal(len(second_fact.axioms()), 40)
assert_equal(len(second_fact.admissions()), 0)
print("Second carrier:")
print(second_fact)
# The base is reused; each polynomial carrier has its own twelve axioms.
assert_equal(len(s.find("Q.", limit=100)), 16)
assert_equal(len(s.find("A.", limit=100)), 13)
assert_equal(len(s.find("B.", limit=100)), 13)
assert_true(first.base.rational(1, 2).same_as(second.base.rational(1, 2)))
assert_true(not first.kind.same_as(second.kind))
assert_equal(len(first_fact.axioms()), 28)
print("Shared base: 16 axioms; original theorem still has 28 dependencies")
# Sharing coefficients does not make the two polynomial types interchangeable.
x = a.indeterminate()
var refused = False
try:
_ = x + y
except error:
refused = error.kind == LibErrorKind.KERNEL
assert_true(refused)
print("Mixed polynomial carriers refused")
Run from the repository root pixi run mojo run -I src docs/examples/library/shared_polynomial_base.mojo
Output
First carrier:
[assuming 28 axioms] ⊢ (1*X[0] + 1) * (1*X[0] - 1) = -1 + 1*X[0]^2
axioms: Q.add_assoc, Q.add_comm, Q.add_zero, Q.mul_assoc, … (+24 more)
Second carrier:
[assuming 40 axioms] ⊢ (1*X[0] + 1) * (1*X[0] - 1) = -1 + 1*X[0]^2
axioms: Q.add_assoc, Q.add_comm, Q.add_zero, Q.mul_assoc, … (+36 more)
Shared base: 16 axioms; original theorem still has 28 dependencies
Mixed polynomial carriers refused
Python
"""Two polynomial carriers share one explicitly assumed rational base."""
from judgment import JudgmentError, LibErrorKind, Session
from exact_arithmetic_setup import numeric_setup
from polynomial_setup import polynomial_setup
def main():
s = Session()
q = numeric_setup(s, "Q", rational=True)
q.register_rationals("rationals")
first = polynomial_setup(s, base_kind=q.kind, carrier_name="First", prefix="A")
a = first.register_polynomials("A.literals")
x = a.indeterminate()
first_proof = s.theorem("A.difference_of_squares", (x + 1) * (x - 1) == a.polynomial([-1, 0, 1]))
first_proof.rfl()
first_fact = first_proof.finish()
assert len(first_fact.axioms()) == 28
assert len(first_fact.admissions()) == 0
print("First carrier:")
print(first_fact)
second = polynomial_setup(s, base_kind=q.kind, carrier_name="Second", prefix="B")
b = second.register_polynomials("B.literals")
y = b.indeterminate()
second_proof = s.theorem("B.difference_of_squares", (y + 1) * (y - 1) == b.polynomial([-1, 0, 1]))
second_proof.rfl()
second_fact = second_proof.finish()
# Its later canonical signature includes both polynomial registrations.
assert len(second_fact.axioms()) == 40
assert len(second_fact.admissions()) == 0
print("Second carrier:")
print(second_fact)
# The base is reused; each polynomial carrier has its own twelve axioms.
assert len(s.find("Q.", limit=100)) == 16
assert len(s.find("A.", limit=100)) == 13
assert len(s.find("B.", limit=100)) == 13
assert first.base.rational(1, 2).same_as(second.base.rational(1, 2))
assert not first.kind.same_as(second.kind)
assert len(first_fact.axioms()) == 28
print("Shared base: 16 axioms; original theorem still has 28 dependencies")
# Sharing coefficients does not make the two polynomial types interchangeable.
x = a.indeterminate()
refused = False
try:
x + y
except JudgmentError as error:
refused = error.kind == LibErrorKind.KERNEL
assert refused
print("Mixed polynomial carriers refused")
main()
Run from the repository root PYTHONPATH=bindings/python:docs/examples/python/library pixi run python docs/examples/python/library/shared_polynomial_base.py
Output
First carrier:
[assuming 28 axioms] ⊢ (1*X[0] + 1) * (1*X[0] - 1) = -1 + 1*X[0]^2
axioms: Q.add_assoc, Q.add_comm, Q.add_zero, Q.mul_assoc, … (+24 more)
Second carrier:
[assuming 40 axioms] ⊢ (1*X[0] + 1) * (1*X[0] - 1) = -1 + 1*X[0]^2
axioms: Q.add_assoc, Q.add_comm, Q.add_zero, Q.mul_assoc, … (+36 more)
Shared base: 16 axioms; original theorem still has 28 dependencies
Mixed polynomial carriers refused
Shared setup modules¶
exact_arithmetic.py, polynomial_arithmetic.py and
shared_polynomial_base.py import these modules:
Mojo
"""Explicit teaching assumptions for reusable exact arithmetic profiles.
These are assumed ordered-ring/field laws over an abstract carrier, not a
construction of the mathematical integers or rationals.
"""
from judgment_shell import Arithmetic, ArithmeticLaws, Expr, LibError, LibErrorKind, Session, TypeExpr, arrow, iff, implies, not_
from ring_assumptions import assume_commutative_ring_laws
@fieldwise_init
struct NumericSetup(Copyable):
"""Typed operations and the complete explicit law bundle."""
var kind: TypeExpr
var numbers: Arithmetic
var lt: Expr
var le: Expr
var inv: Optional[Expr]
var laws: ArithmeticLaws
def register_integers(self, name: String) raises LibError -> Arithmetic:
"""Explicitly enable exact integers using this provider's operations and laws.
Args:
name: The client's fresh literal-kind name and private law-name prefix.
Returns:
The checked Arithmetic profile with canonical integer arithmetic enabled.
Raises:
LibError: For invalid operations, evidence, names, or exhausted work.
Failure publishes no theory or profile change.
"""
return self.numbers.integers(name, self.lt, self.le, self.laws)
def register_rationals(self, name: String) raises LibError -> Arithmetic:
"""Explicitly enable exact rationals using this provider's operations and laws.
Args:
name: The client's fresh literal-kind name and private law-name prefix.
Returns:
The checked Arithmetic profile with canonical rational arithmetic enabled.
Raises:
LibError: UNSUPPORTED if this setup has no inverse; otherwise the
registration's errors for invalid operations, evidence, names,
or exhausted work. Failure publishes no theory or profile change.
"""
if not self.inv:
raise LibError(LibErrorKind.UNSUPPORTED, "rational registration requires a setup with an inverse")
return self.numbers.rationals(name, self.lt, self.le, self.inv.value(), self.laws)
def numeric_setup(mut s: Session, prefix: String, rational: Bool) raises -> NumericSetup:
"""Declare operations and assume each law explicitly, before exact registration."""
var T = s.declare_type(prefix + ".T")
var zero = s.symbol(prefix + ".zero", T)
var one = s.symbol(prefix + ".one", T)
var binary = arrow(T, arrow(T, T))
var add = s.symbol(prefix + ".add", binary)
var mul = s.symbol(prefix + ".mul", binary)
var neg = s.symbol(prefix + ".neg", arrow(T, T))
var relation = arrow(T, arrow(T, s.prop_type()))
var lt = s.symbol(prefix + ".lt", relation)
var le = s.symbol(prefix + ".le", relation)
var inv: Optional[Expr] = None
if rational:
inv = s.symbol(prefix + ".inv", arrow(T, T))
var numbers = s.arithmetic(T, zero, one, add, mul, neg)
var entries = assume_commutative_ring_laws(s, T, zero, one, prefix)
var names: List[String] = ["lt_irrefl", "lt_trans", "lt_total", "lt_add", "lt_mul", "zero_lt_one", "le_iff"]
var arities: List[Int] = [1, 3, 2, 3, 2, 0, 2]
if rational:
names.append("mul_inverse")
arities.append(1)
for i in range(len(names)):
var law = s.axiom(prefix + "." + names[i])
var x = zero
var y = zero
var z = zero
if arities[i] > 0:
x = law.var("x", T)
if arities[i] > 1:
y = law.var("y", T)
if arities[i] > 2:
z = law.var("z", T)
var statement: Expr
if i == 0:
statement = not_(lt(x, x))
elif i == 1:
statement = implies(lt(x, y), implies(lt(y, z), lt(x, z)))
elif i == 2:
statement = lt(x, y) | ((x == y) | lt(y, x))
elif i == 3:
statement = implies(lt(x, y), lt(x + z, y + z))
elif i == 4:
statement = implies(lt(zero, x), implies(lt(zero, y), lt(zero, x * y)))
elif i == 5:
statement = lt(zero, one)
elif i == 6:
statement = iff(le(x, y), lt(x, y) | (x == y))
else:
statement = implies(not_(x == zero), x * inv.value()(x) == one)
entries.append((names[i], law.finish(statement)))
return NumericSetup(T, numbers, lt, le, inv, ArithmeticLaws(entries^))
Python
"""Explicit teaching assumptions for reusable exact arithmetic profiles.
These are assumed ordered-ring/field laws over an abstract carrier, not a
construction of the mathematical integers or rationals.
"""
from __future__ import annotations
from dataclasses import dataclass
from judgment import Arithmetic, ArithmeticLaws, Expr, JudgmentError, LibErrorKind, Session, TypeExpr, arrow, iff, implies, not_
from ring_assumptions import assume_commutative_ring_laws
@dataclass
class NumericSetup:
"""Typed operations and the complete explicit law bundle."""
kind: TypeExpr
numbers: Arithmetic
lt: Expr
le: Expr
inv: Optional[Expr]
laws: ArithmeticLaws
def register_integers(self, name):
"""Explicitly enable exact integers using this provider's operations and laws.
Args:
name: The client's fresh literal-kind name and private law-name prefix.
Returns:
The checked Arithmetic profile with canonical integer arithmetic enabled.
Raises:
LibError: For invalid operations, evidence, names, or exhausted work.
Failure publishes no theory or profile change.
"""
return self.numbers.integers(name, self.lt, self.le, self.laws)
def register_rationals(self, name):
"""Explicitly enable exact rationals using this provider's operations and laws.
Args:
name: The client's fresh literal-kind name and private law-name prefix.
Returns:
The checked Arithmetic profile with canonical rational arithmetic enabled.
Raises:
LibError: UNSUPPORTED if this setup has no inverse; otherwise the
registration's errors for invalid operations, evidence, names,
or exhausted work. Failure publishes no theory or profile change.
"""
if self.inv is None:
raise LibError(LibErrorKind.UNSUPPORTED, "rational registration requires a setup with an inverse")
return self.numbers.rationals(name, self.lt, self.le, self.inv, self.laws)
def numeric_setup(s, prefix, rational):
"""Declare operations and assume each law explicitly, before exact registration."""
T = s.declare_type(prefix + ".T")
zero = s.symbol(prefix + ".zero", T)
one = s.symbol(prefix + ".one", T)
binary = arrow(T, arrow(T, T))
add = s.symbol(prefix + ".add", binary)
mul = s.symbol(prefix + ".mul", binary)
neg = s.symbol(prefix + ".neg", arrow(T, T))
relation = arrow(T, arrow(T, s.prop_type()))
lt = s.symbol(prefix + ".lt", relation)
le = s.symbol(prefix + ".le", relation)
inv = None
if rational:
inv = s.symbol(prefix + ".inv", arrow(T, T))
numbers = s.arithmetic(T, zero, one, add, mul, neg)
entries = assume_commutative_ring_laws(s, T, zero, one, prefix)
names = ["lt_irrefl", "lt_trans", "lt_total", "lt_add", "lt_mul", "zero_lt_one", "le_iff"]
arities = [1, 3, 2, 3, 2, 0, 2]
if rational:
names.append("mul_inverse")
arities.append(1)
for i in range(len(names)):
law = s.axiom(prefix + "." + names[i])
x = zero
y = zero
z = zero
if arities[i] > 0:
x = law.var("x", T)
if arities[i] > 1:
y = law.var("y", T)
if arities[i] > 2:
z = law.var("z", T)
statement = None
if i == 0:
statement = not_(lt(x, x))
elif i == 1:
statement = implies(lt(x, y), implies(lt(y, z), lt(x, z)))
elif i == 2:
statement = lt(x, y) | ((x == y) | lt(y, x))
elif i == 3:
statement = implies(lt(x, y), lt(x + z, y + z))
elif i == 4:
statement = implies(lt(zero, x), implies(lt(zero, y), lt(zero, x * y)))
elif i == 5:
statement = lt(zero, one)
elif i == 6:
statement = iff(le(x, y), lt(x, y) | (x == y))
else:
statement = implies(not_(x == zero), x * inv(x) == one)
entries.append((names[i], law.finish(statement)))
return NumericSetup(T, numbers, lt, le, inv, ArithmeticLaws(entries))
Mojo
"""Shared, explicitly assumed commutative ring laws for arithmetic examples."""
from judgment_shell import Expr, Fact, LibError, Session, TypeExpr
def assume_commutative_ring_laws(
mut s: Session, kind: TypeExpr, zero: Expr, one: Expr, prefix: String,
) raises LibError -> List[Tuple[String, Fact]]:
"""Declare eight named axioms using the carrier's bound arithmetic notation.
Addition, multiplication, and negation must already be bound. Each axiom is
published as prefix.slot. The returned entries can be extended with order
or coefficient laws before constructing ArithmeticLaws. This assumes laws;
it does not prove them or register exact arithmetic.
"""
var names: List[String] = ["add_assoc", "add_comm", "add_zero", "mul_assoc", "mul_comm", "mul_one", "add_inverse", "left_distrib"]
var arities: List[Int] = [3, 2, 1, 3, 2, 1, 1, 3]
var entries = List[Tuple[String, Fact]]()
for i in range(len(names)):
var law = s.axiom(prefix + "." + names[i])
var x = law.var("x", kind)
var y = zero
var z = zero
if arities[i] > 1:
y = law.var("y", kind)
if arities[i] > 2:
z = law.var("z", kind)
var statement: Expr
if i == 0:
statement = (x + y) + z == x + (y + z)
elif i == 1:
statement = x + y == y + x
elif i == 2:
statement = zero + x == x
elif i == 3:
statement = (x * y) * z == x * (y * z)
elif i == 4:
statement = x * y == y * x
elif i == 5:
statement = one * x == x
elif i == 6:
statement = x + (-x) == zero
else:
statement = x * (y + z) == x * y + x * z
entries.append((names[i], law.finish(statement)))
return entries^
Python
"""Shared, explicitly assumed commutative ring laws for arithmetic examples."""
from judgment import Expr, Fact, JudgmentError, Session, TypeExpr
def assume_commutative_ring_laws(s, kind, zero, one, prefix):
"""Declare eight named axioms using the carrier's bound arithmetic notation.
Addition, multiplication, and negation must already be bound. Each axiom is
published as prefix.slot. The returned entries can be extended with order
or coefficient laws before constructing ArithmeticLaws. This assumes laws;
it does not prove them or register exact arithmetic.
"""
names = ["add_assoc", "add_comm", "add_zero", "mul_assoc", "mul_comm", "mul_one", "add_inverse", "left_distrib"]
arities = [3, 2, 1, 3, 2, 1, 1, 3]
entries = []
for i in range(len(names)):
law = s.axiom(prefix + "." + names[i])
x = law.var("x", kind)
y = zero
z = zero
if arities[i] > 1:
y = law.var("y", kind)
if arities[i] > 2:
z = law.var("z", kind)
statement = None
if i == 0:
statement = (x + y) + z == x + (y + z)
elif i == 1:
statement = x + y == y + x
elif i == 2:
statement = zero + x == x
elif i == 3:
statement = (x * y) * z == x * (y * z)
elif i == 4:
statement = x * y == y * x
elif i == 5:
statement = one * x == x
elif i == 6:
statement = x + (-x) == zero
else:
statement = x * (y + z) == x * y + x * z
entries.append((names[i], law.finish(statement)))
return entries
Mojo
"""Explicit teaching axioms for formal polynomials over an exact rational base."""
from judgment_shell import Arithmetic, ArithmeticLaws, Expr, LibError, Session, TypeExpr, arrow
from exact_arithmetic_setup import numeric_setup
from ring_assumptions import assume_commutative_ring_laws
@fieldwise_init
struct PolynomialSetup(Copyable):
"""The polynomial carrier, exact base, and checked registration inputs."""
var kind: TypeExpr
var numbers: Arithmetic
var base: Arithmetic
var coeff: Expr
var indet: Expr
var laws: ArithmeticLaws
def register_polynomials(self, name: String) raises LibError -> Arithmetic:
"""Explicitly enable polynomial literals using this provider's base and laws.
Args:
name: The client's fresh literal-kind name and private law-name prefix.
Returns:
The checked Arithmetic profile with canonical polynomial arithmetic enabled.
Raises:
LibError: For invalid owners, operations, evidence, names, or exhausted
work. Failure publishes no theory or profile change.
"""
return self.numbers.polynomials(name, self.base, self.coeff, self.indet, self.laws)
def polynomial_setup(
mut s: Session, base_kind: TypeExpr,
carrier_name: String = "Polynomial", prefix: String = "P",
) raises LibError -> PolynomialSetup:
"""Assume polynomial laws over an existing exact rational base.
The base must belong to this session and already support exact rationals.
Check it before publishing the polynomial carrier or its assumptions.
The caller chooses fresh names and explicitly registers polynomial literals.
"""
var base = s.arithmetic(base_kind)
_ = base.rational(0, 1)
var P = s.declare_type(carrier_name)
var zero = s.symbol(prefix + ".zero", P)
var one = s.symbol(prefix + ".one", P)
var binary = arrow(P, arrow(P, P))
var add = s.symbol(prefix + ".add", binary)
var mul = s.symbol(prefix + ".mul", binary)
var neg = s.symbol(prefix + ".neg", arrow(P, P))
var coeff = s.symbol(prefix + ".coeff", arrow(base_kind, P))
var indet = s.symbol(prefix + ".indet", arrow(base_kind, P))
var numbers = s.arithmetic(P, zero, one, add, mul, neg)
var entries = assume_commutative_ring_laws(s, P, zero, one, prefix)
var names: List[String] = ["coeff_zero", "coeff_one", "coeff_add", "coeff_mul"]
var arities: List[Int] = [0, 0, 2, 2]
for i in range(len(names)):
var law = s.axiom(prefix + "." + names[i])
var x = zero
var y = zero
if arities[i] > 0:
x = law.var("x", base_kind)
if arities[i] > 1:
y = law.var("y", base_kind)
var statement: Expr
if i == 0:
statement = coeff(base.number(0)) == zero
elif i == 1:
statement = coeff(base.number(1)) == one
elif i == 2:
statement = coeff(x + y) == coeff(x) + coeff(y)
else:
statement = coeff(x * y) == coeff(x) * coeff(y)
entries.append((names[i], law.finish(statement)))
return PolynomialSetup(P, numbers, base, coeff, indet, ArithmeticLaws(entries^))
def polynomial_setup(mut s: Session) raises -> PolynomialSetup:
"""Create the original Q base and Polynomial fixture with explicit axioms."""
var q = numeric_setup(s, "Q", rational=True)
_ = q.register_rationals("rationals")
return polynomial_setup(s, base_kind=q.kind)
Python
"""Explicit teaching axioms for formal polynomials over an exact rational base."""
from dataclasses import dataclass
from judgment import Arithmetic, ArithmeticLaws, Expr, Session, TypeExpr, arrow
from exact_arithmetic_setup import numeric_setup
from ring_assumptions import assume_commutative_ring_laws
@dataclass
class PolynomialSetup:
"""The polynomial carrier, exact base, and checked registration inputs."""
kind: TypeExpr
numbers: Arithmetic
base: Arithmetic
coeff: Expr
indet: Expr
laws: ArithmeticLaws
def register_polynomials(self, name):
"""Explicitly enable polynomial literals using this provider's base and laws.
Args:
name: The client's fresh literal-kind name and private law-name prefix.
Returns:
The checked Arithmetic profile with canonical polynomial arithmetic enabled.
Raises:
JudgmentError: For invalid owners, operations, evidence, names, or exhausted
work. Failure publishes no theory or profile change.
"""
return self.numbers.polynomials(name, self.base, self.coeff, self.indet, self.laws)
def polynomial_setup(s, base_kind=None, carrier_name="Polynomial", prefix="P"):
"""Assume polynomial laws over an existing exact rational base.
The base must belong to this session and already support exact rationals.
Check it before publishing the polynomial carrier or its assumptions.
The caller chooses fresh names and explicitly registers polynomial literals.
Without `base_kind`, it first creates the original Q base with explicit axioms.
"""
if base_kind is None:
q = numeric_setup(s, "Q", rational=True)
q.register_rationals("rationals")
base_kind = q.kind
base = s.arithmetic(base_kind)
base.rational(0, 1)
P = s.declare_type(carrier_name)
zero = s.symbol(prefix + ".zero", P)
one = s.symbol(prefix + ".one", P)
binary = arrow(P, arrow(P, P))
add = s.symbol(prefix + ".add", binary)
mul = s.symbol(prefix + ".mul", binary)
neg = s.symbol(prefix + ".neg", arrow(P, P))
coeff = s.symbol(prefix + ".coeff", arrow(base_kind, P))
indet = s.symbol(prefix + ".indet", arrow(base_kind, P))
numbers = s.arithmetic(P, zero, one, add, mul, neg)
entries = assume_commutative_ring_laws(s, P, zero, one, prefix)
names = ["coeff_zero", "coeff_one", "coeff_add", "coeff_mul"]
arities = [0, 0, 2, 2]
for i in range(len(names)):
law = s.axiom(prefix + "." + names[i])
x = law.var("x", base_kind) if arities[i] > 0 else zero
y = law.var("y", base_kind) if arities[i] > 1 else zero
if i == 0:
statement = coeff(base.number(0)) == zero
elif i == 1:
statement = coeff(base.number(1)) == one
elif i == 2:
statement = coeff(x + y) == coeff(x) + coeff(y)
else:
statement = coeff(x * y) == coeff(x) * coeff(y)
entries.append((names[i], law.finish(statement)))
return PolynomialSetup(P, numbers, base, coeff, indet, ArithmeticLaws(entries))
Exact numbers and Scalar¶
Compute rational and polynomial literals under explicitly declared laws¶
Rationals are ints and Fractions; integers of any size cross exactly.
Mojo
"""Compute rational and polynomial literals under explicitly declared laws."""
from apn_mojo import Integer, Rational
from std.testing import assert_true
from judgment import Session
from judgment_shell import LibErrorKind
from arithmetic_theory import arithmetic_theory
def main() raises:
var s = Session()
var numbers = arithmetic_theory(s)
var half = numbers.rational.rational(1, 2)
var third = numbers.rational.rational(1, 3)
var sum_def = s.define("half_plus_third", half + third)
var five_sixths = numbers.rational.rational(5, 6)
assert_true((half + third).same_as(five_sixths))
assert_true(numbers.rational.number(0).same_as(numbers.rational.rational(0, 1)))
assert_true(numbers.rational.inverse(numbers.rational.number(0)).format() == "Q.inv(0)")
var sum_proof = s.theorem("rational_sum", sum_def.symbol() == five_sixths)
sum_proof.change(five_sixths == five_sixths, unfold=[sum_def])
sum_proof.rfl()
var sum_fact = sum_proof.finish()
assert_true(len(sum_fact.axioms()) > 0)
var x = numbers.polynomial.indeterminate(0)
var one = numbers.polynomial.number(1)
var product = (x + one) * (x - one)
# Hand-written canonical coefficients: -1 + X[0]^2, independent of multiplication.
var expected = numbers.polynomial.polynomial([
Rational(Integer(-1)), Rational(Integer(0)), Rational(Integer(1)),
])
assert_true(product.same_as(expected))
var poly_proof = s.theorem("difference_of_squares", product == expected)
poly_proof.rfl()
var poly_fact = poly_proof.finish()
assert_true(poly_fact.statement().same_as(product == expected))
assert_true(len(poly_fact.axioms()) > 0)
# A polynomial indeterminate is data inside a literal. A variable is a symbolic term.
var sym = s.theorem("symbolic_distribution")
var p = sym.var("p", numbers.polynomial_type)
var symbolic = p * (p + one)
var expanded = p * p + p
assert_true(not symbolic.same_as(expanded))
sym.goal(symbolic == expanded)
var refused = False
try:
sym.rfl()
except e:
refused = e.kind == LibErrorKind.KERNEL or e.kind == LibErrorKind.SHAPE
assert_true(refused)
print("Rational literals: 1/2 + 1/3 = 5/6")
print("Inverse of zero: left unevaluated")
print("Polynomial literals: (X[0] + 1)(X[0] - 1) = X[0]^2 - 1")
print("Symbolic distribution: requires a theorem")
Run from the repository root pixi run mojo run -I src docs/examples/arithmetic.mojo
Output
Rational literals: 1/2 + 1/3 = 5/6
Inverse of zero: left unevaluated
Polynomial literals: (X[0] + 1)(X[0] - 1) = X[0]^2 - 1
Symbolic distribution: requires a theorem
Python
"""Compute rational and polynomial literals under explicitly declared laws."""
from judgment import JudgmentError, LibErrorKind, Session
from arithmetic_theory import arithmetic_theory
def main():
s = Session()
numbers = arithmetic_theory(s)
half = numbers.rational.rational(1, 2)
third = numbers.rational.rational(1, 3)
sum_def = s.define("half_plus_third", half + third)
five_sixths = numbers.rational.rational(5, 6)
assert (half + third).same_as(five_sixths)
assert numbers.rational.number(0).same_as(numbers.rational.rational(0, 1))
assert numbers.rational.inverse(numbers.rational.number(0)).format() == "Q.inv(0)"
sum_proof = s.theorem("rational_sum", sum_def.symbol() == five_sixths)
sum_proof.change(five_sixths == five_sixths, unfold=[sum_def])
sum_proof.rfl()
sum_fact = sum_proof.finish()
assert len(sum_fact.axioms()) > 0
x = numbers.polynomial.indeterminate(0)
one = numbers.polynomial.number(1)
product = (x + one) * (x - one)
# Hand-written canonical coefficients: -1 + X[0]^2, independent of multiplication.
expected = numbers.polynomial.polynomial([-1, 0, 1])
assert product.same_as(expected)
poly_proof = s.theorem("difference_of_squares", product == expected)
poly_proof.rfl()
poly_fact = poly_proof.finish()
assert poly_fact.statement().same_as(product == expected)
assert len(poly_fact.axioms()) > 0
# A polynomial indeterminate is data inside a literal. A variable is a symbolic term.
sym = s.theorem("symbolic_distribution")
p = sym.var("p", numbers.polynomial_type)
symbolic = p * (p + one)
expanded = p * p + p
assert not symbolic.same_as(expanded)
sym.goal(symbolic == expanded)
refused = False
try:
sym.rfl()
except JudgmentError as e:
refused = e.kind == LibErrorKind.KERNEL or e.kind == LibErrorKind.SHAPE
assert refused
print("Rational literals: 1/2 + 1/3 = 5/6")
print("Inverse of zero: left unevaluated")
print("Polynomial literals: (X[0] + 1)(X[0] - 1) = X[0]^2 - 1")
print("Symbolic distribution: requires a theorem")
main()
Run from the repository root PYTHONPATH=bindings/python:docs/examples/python pixi run python docs/examples/python/arithmetic.py
Output
Rational literals: 1/2 + 1/3 = 5/6
Inverse of zero: left unevaluated
Polynomial literals: (X[0] + 1)(X[0] - 1) = X[0]^2 - 1
Symbolic distribution: requires a theorem
arithmetic.py imports its teaching theory:
Mojo
"""An explicit teaching theory: rational and polynomial arithmetic with admitted laws.
These helpers only call the public Session API. They declare the field and
polynomial laws as AXIOMS, not as proved facts or imported library theorems.
The complete assumptions are visible below. This is example setup, not a
bundled standard number theory or a replacement for a theorem library.
"""
from judgment import Arithmetic, ArithmeticLaws, Expr, Fact, Session, TypeExpr, arrow, iff, implies, not_
def assume_ring_laws(
mut s: Session, carrier: TypeExpr, zero: Expr, one: Expr, prefix: String,
) raises -> List[Tuple[String, Fact]]:
"""Assume the eight commutative ring laws on a carrier with bound arithmetic."""
var names: List[String] = [
"add_assoc", "add_comm", "add_zero",
"mul_assoc", "mul_comm", "mul_one",
"add_inverse", "left_distrib",
]
var arities: List[Int] = [3, 2, 1, 3, 2, 1, 1, 3]
var entries = List[Tuple[String, Fact]]()
for i in range(len(names)):
var law = s.axiom(prefix + "." + names[i])
var x = law.var("x", carrier)
var y = zero
var z = zero
if arities[i] > 1:
y = law.var("y", carrier)
if arities[i] > 2:
z = law.var("z", carrier)
var statement: Expr
if i == 0:
statement = (x + y) + z == x + (y + z)
elif i == 1:
statement = x + y == y + x
elif i == 2:
statement = zero + x == x
elif i == 3:
statement = (x * y) * z == x * (y * z)
elif i == 4:
statement = x * y == y * x
elif i == 5:
statement = one * x == x
elif i == 6:
statement = x + (-x) == zero
else:
statement = x * (y + z) == x * y + x * z
entries.append((names[i], law.finish(statement)))
return entries^
@fieldwise_init
struct ArithmeticTheory(Copyable):
"""The example's rational base profile and formal-polynomial profile."""
var rational_type: TypeExpr
var rational: Arithmetic
var polynomial_type: TypeExpr
var polynomial: Arithmetic
def arithmetic_theory(mut s: Session) raises -> ArithmeticTheory:
"""Build the teaching theory, with every mathematical law explicitly admitted."""
var q_type = s.declare_type("Q.T")
var q_zero = s.symbol("Q.zero", q_type)
var q_one = s.symbol("Q.one", q_type)
var q_bin = arrow(q_type, arrow(q_type, q_type))
var q_add = s.symbol("Q.add", q_bin)
var q_mul = s.symbol("Q.mul", q_bin)
var q_neg = s.symbol("Q.neg", arrow(q_type, q_type))
var q_cmp = arrow(q_type, arrow(q_type, s.prop_type()))
var q_lt = s.symbol("Q.lt", q_cmp)
var q_le = s.symbol("Q.le", q_cmp)
var q_inv = s.symbol("Q.inv", arrow(q_type, q_type))
var q_profile = s.arithmetic(q_type, q_zero, q_one, q_add, q_mul, q_neg)
var q_laws = assume_ring_laws(s, q_type, q_zero, q_one, "Q")
var q_names: List[String] = [
"lt_irrefl", "lt_trans", "lt_total", "lt_add", "lt_mul", "zero_lt_one", "le_iff", "mul_inverse",
]
var q_arities: List[Int] = [1, 3, 2, 3, 2, 0, 2, 1]
for i in range(len(q_names)):
var law = s.axiom("Q." + q_names[i])
var x = q_zero
var y = q_zero
var z = q_zero
if q_arities[i] > 0:
x = law.var("x", q_type)
if q_arities[i] > 1:
y = law.var("y", q_type)
if q_arities[i] > 2:
z = law.var("z", q_type)
var statement: Expr
if i == 0:
statement = not_(q_lt(x, x))
elif i == 1:
statement = implies(q_lt(x, y), implies(q_lt(y, z), q_lt(x, z)))
elif i == 2:
statement = q_lt(x, y) | ((x == y) | q_lt(y, x))
elif i == 3:
statement = implies(q_lt(x, y), q_lt(x + z, y + z))
elif i == 4:
statement = implies(q_lt(q_zero, x), implies(q_lt(q_zero, y), q_lt(q_zero, x * y)))
elif i == 5:
statement = q_lt(q_zero, q_one)
elif i == 6:
statement = iff(q_le(x, y), q_lt(x, y) | (x == y))
else:
statement = implies(not_(x == q_zero), x * q_inv(x) == q_one)
q_laws.append((q_names[i], law.finish(statement)))
var rationals = q_profile.rationals("rationals", q_lt, q_le, q_inv, ArithmeticLaws(q_laws^))
var p_type = s.declare_type("P.T")
var p_zero = s.symbol("P.zero", p_type)
var p_one = s.symbol("P.one", p_type)
var p_bin = arrow(p_type, arrow(p_type, p_type))
var p_add = s.symbol("P.add", p_bin)
var p_mul = s.symbol("P.mul", p_bin)
var p_neg = s.symbol("P.neg", arrow(p_type, p_type))
var p_coeff = s.symbol("P.coeff", arrow(q_type, p_type))
var p_indet = s.symbol("P.indeterminate", arrow(q_type, p_type))
var p_profile = s.arithmetic(p_type, p_zero, p_one, p_add, p_mul, p_neg)
var p_laws = assume_ring_laws(s, p_type, p_zero, p_one, "P")
var p_names: List[String] = ["coeff_zero", "coeff_one", "coeff_add", "coeff_mul"]
var p_arities: List[Int] = [0, 0, 2, 2]
for i in range(len(p_names)):
var law = s.axiom("P." + p_names[i])
var a = q_zero
var c = q_zero
if p_arities[i] > 0:
a = law.var("a", q_type)
if p_arities[i] > 1:
c = law.var("c", q_type)
var statement: Expr
if i == 0:
statement = p_coeff(rationals.number(0)) == p_zero
elif i == 1:
statement = p_coeff(rationals.number(1)) == p_one
elif i == 2:
statement = p_coeff(a + c) == p_coeff(a) + p_coeff(c)
else:
statement = p_coeff(a * c) == p_coeff(a) * p_coeff(c)
p_laws.append((p_names[i], law.finish(statement)))
var polynomials = p_profile.polynomials("polynomials", rationals, p_coeff, p_indet, ArithmeticLaws(p_laws^))
return ArithmeticTheory(q_type, rationals, p_type, polynomials)
Python
"""An explicit teaching theory: rational and polynomial arithmetic with admitted laws.
These helpers only call the public Session API. They declare the field and
polynomial laws as AXIOMS, not as proved facts or imported library theorems.
The complete assumptions are visible below. This is example setup, not a
bundled standard number theory or a replacement for a theorem library.
"""
from dataclasses import dataclass
from judgment import Arithmetic, ArithmeticLaws, Session, TypeExpr, arrow, iff, implies, not_
def assume_ring_laws(s, carrier, zero, one, prefix):
"""Assume the eight commutative ring laws on a carrier with bound arithmetic."""
names = ["add_assoc", "add_comm", "add_zero", "mul_assoc", "mul_comm", "mul_one", "add_inverse", "left_distrib"]
arities = [3, 2, 1, 3, 2, 1, 1, 3]
entries = []
for i, name in enumerate(names):
law = s.axiom(prefix + "." + name)
x = law.var("x", carrier)
y = law.var("y", carrier) if arities[i] > 1 else zero
z = law.var("z", carrier) if arities[i] > 2 else zero
if i == 0:
statement = (x + y) + z == x + (y + z)
elif i == 1:
statement = x + y == y + x
elif i == 2:
statement = zero + x == x
elif i == 3:
statement = (x * y) * z == x * (y * z)
elif i == 4:
statement = x * y == y * x
elif i == 5:
statement = one * x == x
elif i == 6:
statement = x + (-x) == zero
else:
statement = x * (y + z) == x * y + x * z
entries.append((name, law.finish(statement)))
return entries
@dataclass
class ArithmeticTheory:
"""The example's rational base profile and formal-polynomial profile."""
rational_type: TypeExpr
rational: Arithmetic
polynomial_type: TypeExpr
polynomial: Arithmetic
def arithmetic_theory(s: Session) -> ArithmeticTheory:
"""Build the teaching theory, with every mathematical law explicitly admitted."""
q_type = s.declare_type("Q.T")
q_zero = s.symbol("Q.zero", q_type)
q_one = s.symbol("Q.one", q_type)
q_bin = arrow(q_type, arrow(q_type, q_type))
q_add = s.symbol("Q.add", q_bin)
q_mul = s.symbol("Q.mul", q_bin)
q_neg = s.symbol("Q.neg", arrow(q_type, q_type))
q_cmp = arrow(q_type, arrow(q_type, s.prop_type()))
q_lt = s.symbol("Q.lt", q_cmp)
q_le = s.symbol("Q.le", q_cmp)
q_inv = s.symbol("Q.inv", arrow(q_type, q_type))
q_profile = s.arithmetic(q_type, q_zero, q_one, q_add, q_mul, q_neg)
q_laws = assume_ring_laws(s, q_type, q_zero, q_one, "Q")
q_names = ["lt_irrefl", "lt_trans", "lt_total", "lt_add", "lt_mul", "zero_lt_one", "le_iff", "mul_inverse"]
q_arities = [1, 3, 2, 3, 2, 0, 2, 1]
for i, name in enumerate(q_names):
law = s.axiom("Q." + name)
x = law.var("x", q_type) if q_arities[i] > 0 else q_zero
y = law.var("y", q_type) if q_arities[i] > 1 else q_zero
z = law.var("z", q_type) if q_arities[i] > 2 else q_zero
if i == 0:
statement = not_(q_lt(x, x))
elif i == 1:
statement = implies(q_lt(x, y), implies(q_lt(y, z), q_lt(x, z)))
elif i == 2:
statement = q_lt(x, y) | ((x == y) | q_lt(y, x))
elif i == 3:
statement = implies(q_lt(x, y), q_lt(x + z, y + z))
elif i == 4:
statement = implies(q_lt(q_zero, x), implies(q_lt(q_zero, y), q_lt(q_zero, x * y)))
elif i == 5:
statement = q_lt(q_zero, q_one)
elif i == 6:
statement = iff(q_le(x, y), q_lt(x, y) | (x == y))
else:
statement = implies(not_(x == q_zero), x * q_inv(x) == q_one)
q_laws.append((name, law.finish(statement)))
rationals = q_profile.rationals("rationals", q_lt, q_le, q_inv, ArithmeticLaws(q_laws))
p_type = s.declare_type("P.T")
p_zero = s.symbol("P.zero", p_type)
p_one = s.symbol("P.one", p_type)
p_bin = arrow(p_type, arrow(p_type, p_type))
p_add = s.symbol("P.add", p_bin)
p_mul = s.symbol("P.mul", p_bin)
p_neg = s.symbol("P.neg", arrow(p_type, p_type))
p_coeff = s.symbol("P.coeff", arrow(q_type, p_type))
p_indet = s.symbol("P.indeterminate", arrow(q_type, p_type))
p_profile = s.arithmetic(p_type, p_zero, p_one, p_add, p_mul, p_neg)
p_laws = assume_ring_laws(s, p_type, p_zero, p_one, "P")
p_names = ["coeff_zero", "coeff_one", "coeff_add", "coeff_mul"]
p_arities = [0, 0, 2, 2]
for i, name in enumerate(p_names):
law = s.axiom("P." + name)
a = law.var("a", q_type) if p_arities[i] > 0 else q_zero
c = law.var("c", q_type) if p_arities[i] > 1 else q_zero
if i == 0:
statement = p_coeff(rationals.number(0)) == p_zero
elif i == 1:
statement = p_coeff(rationals.number(1)) == p_one
elif i == 2:
statement = p_coeff(a + c) == p_coeff(a) + p_coeff(c)
else:
statement = p_coeff(a * c) == p_coeff(a) * p_coeff(c)
p_laws.append((name, law.finish(statement)))
polynomials = p_profile.polynomials("polynomials", rationals, p_coeff, p_indet, ArithmeticLaws(p_laws))
return ArithmeticTheory(q_type, rationals, p_type, polynomials)
Build the Scalar profile and open a Scalar session¶
Mojo
"""Build the basic Scalar profile and give a session symbol its default finiteness assumption."""
from scalar import ProfileLevel, build_scalar, default_context, session
from std.testing import assert_equal, assert_false
from termbank import Budget
def main() raises:
var budget = Budget(10_000_000)
var profile = build_scalar(budget, ProfileLevel.FOUNDATION)
assert_false(profile.has_literal_kind())
var s = session(profile, ["x"], work=1_000_000)
_ = default_context(s)
assert_equal(len(profile.definitions()), 8)
assert_equal(len(profile.theorems()), 8)
print("Foundation: 8 definitions, 8 proofs, 1 finite session symbol")
Run from the repository root pixi run mojo run -I src docs/examples/scalar/build_foundation.mojo
Output
Foundation: 8 definitions, 8 proofs, 1 finite session symbol
Python
"""Build the basic Scalar profile and give a session symbol its default finiteness assumption."""
from judgment import Budget, ProfileLevel, build_scalar, default_context, session
def main():
budget = Budget(10_000_000)
profile = build_scalar(budget, ProfileLevel.FOUNDATION)
assert not profile.has_literal_kind()
s = session(profile, ["x"], work=1_000_000)
_ = default_context(s)
assert len(profile.definitions()) == 8
assert len(profile.theorems()) == 8
print("Foundation: 8 definitions, 8 proofs, 1 finite session symbol")
main()
Run from the repository root PYTHONPATH=bindings/python:docs/examples/python/scalar pixi run python docs/examples/python/scalar/build_foundation.py
Output
Foundation: 8 definitions, 8 proofs, 1 finite session symbol
The Store¶
Read a published library, recheck it, and import a theorem into a session¶
The program reads the library that the Mojo example publishes; the
documentation gate publishes it and passes its path in
JUDGMENT_EXAMPLE_LIBRARY.
Mojo
"""Load a published proof-DAG library, recheck it, open a session snapshot, and import theorems."""
from std.tempfile import mkdtemp
from std.testing import assert_equal, assert_true
from judgment_shell import Session
from judgment_store import Library, StoreErrorKind
from termbank import Budget
def publish_example(path: String) raises:
var lib = Library.create(path, "none")
var budget = Budget(10000000)
var s = Session.open(lib.profile_snapshot(budget))
var t_fact = s.prove_step("basics.truth", s.truth(s.base()))
var t_step = s.truth(s.base())
var both_fact = s.prove_step("pairs.both", s.and_intro(t_step, t_step))
var change = lib.change()
change.add(s.export(t_fact, "basics.truth"))
change.add(s.export(both_fact, "pairs.both"))
_ = change.publish()
def main() raises:
var path = String(mkdtemp(), "/lib")
publish_example(path)
# Open the library and independently recheck every stored proof row.
var lib = Library.open(path)
var budget = Budget(10000000)
var check = lib.recheck(budget, workers=1)
assert_equal(len(lib.theorems()), 2)
assert_true(check.rows > 0)
print("Rechecked", len(lib.theorems()), "theorems")
# Look up a theorem by name or by canonical statement identity.
var info = lib.find("pairs.both").value().copy()
assert_true(Bool(lib.find(String("judgment.stmt.", info.sid))))
assert_true(not lib.find("pairs.none"))
print("Found pairs.both:", info.name, "| unknown absent:", not lib.find("pairs.none"))
# Open a session over the full rechecked snapshot and cite the theorem.
var snap = lib.snapshot(budget, workers=1)
var s = Session.open(snap)
var fact = s.import_fact("pairs.both")
print("Cited from snapshot:", fact)
# Opening a non-existent library directory fails with a typed StoreError.
var refused = String("accepted")
try:
_ = Library.open(String(path, "/missing"))
except error:
refused = String(error.kind)
assert_true(refused != "accepted")
print("Missing library refused:", refused)
Run from the repository root pixi run mojo run -I src docs/examples/store/load_library.mojo
Output
Rechecked 2 theorems
Found pairs.both: pairs.both | unknown absent: True
Cited from snapshot: ⊢ True ∧ True
Missing library refused: MISSING_DEPENDENCY
Python
"""Load a published proof-DAG library, recheck it, open a session snapshot, and import theorems.
This example opens the library that `docs/examples/store/load_library.mojo`
publishes in `publish_example`, at the path in `JUDGMENT_EXAMPLE_LIBRARY` (the
documentation gate publishes it there). See `binary_roundtrip.py` to create and
publish a library from Python.
"""
import os
from judgment import Budget, Library, Session, StoreError
def main():
path = os.environ["JUDGMENT_EXAMPLE_LIBRARY"]
# Open the library and independently recheck every stored proof row.
lib = Library.open(path)
budget = Budget(10000000)
check = lib.recheck(budget, workers=1)
assert len(lib.theorems()) == 2
assert check.rows > 0
print("Rechecked", len(lib.theorems()), "theorems")
# Look up a theorem by name or by canonical statement identity.
info = lib.find("pairs.both")
assert lib.find(f"judgment.stmt.{info.sid}") is not None
assert lib.find("pairs.none") is None
print("Found pairs.both:", info.name, "| unknown absent:", lib.find("pairs.none") is None)
# Open a session over the full rechecked snapshot and cite the theorem.
snap = lib.snapshot(budget, workers=1)
s = Session.open(snap)
fact = s.import_fact("pairs.both")
print("Cited from snapshot:", fact)
# Opening a non-existent library directory fails with a typed StoreError.
refused = "accepted"
try:
Library.open(path + "/missing")
except StoreError as error:
refused = str(error.kind)
assert refused != "accepted"
print("Missing library refused:", refused)
main()
Run from the repository root PYTHONPATH=bindings/python:docs/examples/python/store pixi run python docs/examples/python/store/load_library.py
Output
Rechecked 2 theorems
Found pairs.both: pairs.both | unknown absent: True
Cited from snapshot: ⊢ True ∧ True
Missing library refused: MISSING_DEPENDENCY