Part 4 — Symbolic math, Scalar & naturals

4.1 Compute exact arithmetic and polynomial literals

Tutorial sequence · Previous: 3.4 Class hierarchies, subsets, and custom ACU

Use literal arithmetic when an expression's operands are known exact values. This tutorial adds 1/2 and 1/3, multiplies two formal polynomials, and proves the resulting equalities. It also shows two cases that stay unevaluated: an inverse of zero and a symbolic distribution.

A new session supplies logic. It does not choose a number system for your application. The example therefore has a setup module that declares carriers, operations, and the laws used by the arithmetic implementation.

Know the assumptions

The example's arithmetic_theory helper registers an abstract ordered field with rational literals and a formal-polynomial kind over that field. It admits the mathematical laws as axioms. The kernel checks their types and required shapes; it does not prove these assumptions consistent. This setup does not uniquely characterize the field as the standard rationals, and it does not import a standard mathematical library.

The helper is included with the example and uses only public APIs. Keep arithmetic.mojo and arithmetic_theory.mojo together if you download them. The complete setup shows every admitted law. A theorem library can instead supply proved law facts with the same statements.

Mojo

arithmetic.mojo Download
"""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

arithmetic.py Download
"""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

Register operations, then construct values

Arithmetic.rationals and Arithmetic.polynomials connect a carrier's bound operations to named law facts and return the carrier's exact profile. This example enables exact rationals and formal polynomials; Arithmetic.integers enables exact integers, with the ordered-ring laws described in the conversion theory.

Once a profile is registered, rational(1, 2) and number(1) construct exact values, and arithmetic on literal operands folds during construction. Thus half + third is already the same expression as rational(5, 6) when it is built, and number(0) is the same expression as rational(0, 1).

A definition can still name the unevaluated form. The theorem rational_sum states that half_plus_third equals 5/6; change unfolds the definition and rfl closes the goal. Its axioms() are not empty: the proof rests on the admitted laws that justify literal folding.

The inverse law only determines the result for nonzero operands. The inverse of zero therefore remains the application Q.inv(0). It is not silently assigned zero or infinity.

Separate polynomial data from symbolic terms

indeterminate(0) constructs the formal indeterminate X[0] as literal data. A complete polynomial is one literal with a canonical sparse coefficient representation. It can contain indeterminates and still be a literal.

Multiplying (X[0] + 1) and (X[0] - 1) produces X[0]^2 - 1. The assertion compares it with polynomial([-1, 0, 1]), whose coefficients are written by hand in ascending degree, rather than calling multiplication again to manufacture the expected answer. rfl proves the equality, and the theorem again rests on the admitted laws.

A header parameter p of polynomial type is different: it stands for an arbitrary polynomial, with no known coefficient list. The expression p * (p + 1) does not evaluate to a literal, and conversion does not distribute it into p * p + p: rfl is refused. That identity requires the distributivity law, used through ordinary proof steps. A refused rfl is not a proof that the expressions are unequal.

Choose the right arithmetic layer

Use apn_mojo directly for numeric computation that does not need a logical judgment. Use judgment's literal kinds when exact computation is part of a checked symbolic derivation. Results of external algorithms (such as polynomial factorization) still need evidence; see integration contracts.

Next: 4.2 Extended complex numbers with Scalar.

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