Tutorials

Part 1: First steps — constraints, models, and exact numbers

In this first tutorial you will build a small scheduling puzzle, enumerate every valid solution, and see how z3_mojo handles exact arbitrary-precision rationals versus irrational algebraic roots.

Full runnable file: docs/examples/tutorial_01_first_steps.mojo.

1. Contexts, variables, and your first solver

Every Z3 expression (Ast) belongs to a Context. Unlike Python's z3-solver, there is no hidden global context, so you always pass ctx when creating variables or numerals:

from std.testing import assert_equal
from z3_mojo import Context, Distinct, Eq, Ints, Solver, sat

var ctx = Context()
var slots = Ints("a b c d", ctx)
var a = slots[0]
var b = slots[1]
var c = slots[2]
var d = slots[3]

Suppose we need to schedule four conference talks (a, b, c, d) into time slots 1..4 such that:

  • all four talks occupy distinct slots,
  • Talk A finishes before Talk B (a < b),
  • Talk C immediately follows Talk D (c == d + 1),
  • Talk D is not in slot 1 (d > 1).

Add the constraints to a Solver(ctx) and call s.check():

var s = Solver(ctx)
for i in range(4):
    s.add(slots[i] >= 1, slots[i] <= 4)
s.add(
    Distinct(slots),
    a < b,
    Eq(c, d + 1),
    d > 1,
)

assert_equal(s.check(), sat)
var m = s.model()
print(
    "Schedule -> A:", m.get_integer(a).value(),
    "B:", m.get_integer(b).value(),
    "C:", m.get_integer(c).value(),
    "D:", m.get_integer(d).value(),
)

Three Mojo habits to remember right from the start:

  1. Use Eq(a, b) and Ne(a, b) for Z3 equalities. In Mojo, a == b is Equatable structural AST identity returning Bool, not a Z3 formula.
  2. Put the Ast on the left of <, <=, >, >=. Arithmetic operators coerce literals on either side (2 * x + 1), while comparison operators dispatch on the left operand (d > 1, not 1 < d).
  3. Single Int/Bool/String variables are IntVar, BoolVar, StringVar. This avoids shadowing Mojo's built-in Int, Bool, and String types.

2. Enumerating every solution

Often you want more than one satisfying assignment. Solver.solutions blocks each found model internally and collects every distinct assignment up to a bound (max_solutions=1000 by default):

var all_schedules = s.solutions(slots)
assert_equal(len(all_schedules), 2)
print("Total valid schedules:", len(all_schedules))

Running the puzzle prints:

Schedule -> A: 1 B: 2 C: 4 D: 3
Total valid schedules: 2

3. Exact rationals vs irrational algebraic roots

Z3 solves nonlinear real polynomial constraints exactly via its qfnra-nlsat tactic. Model values convert losslessly to apn_mojo.Rational without passing through IEEE-754 floats:

from apn_mojo import Rational
from z3_mojo import Real

var s_real = Solver.from_tactic(ctx, "qfnra-nlsat")
var x = Real("x", ctx)
var y = Real("y", ctx)
s_real.add(Eq(x * x + y * y, 1), Eq(x, Rational(3, 5)), y > 0)

assert_equal(s_real.check(), sat)
var mr = s_real.model()
assert_equal(mr.get_rational(y).value(), Rational(4, 5))
print("Exact rational point: x =", mr.get_rational(x).value(), ", y =", mr.get_rational(y).value())

What if the only solution is irrational, like the positive root of r^2 = 2? z3_mojo refuses to silently round it: m.get_rational(r) returns None, and m[r].value().is_algebraic_number() is True:

var s_irr = Solver.from_tactic(ctx, "qfnra-nlsat")
var r = Real("r", ctx)
s_irr.add(Eq(r * r, 2), r > 0)
assert_equal(s_irr.check(), sat)

var m_irr = s_irr.model()
var r_ast = m_irr[r].value()
assert_true(r_ast.is_algebraic_number())
assert_false(Bool(m_irr.get_rational(r)))
print("Irrational root (exact algebraic AST):", r_ast)

Output:

Exact rational point: x = 3/5 , y = 4/5
Irrational root (exact algebraic AST): (root-obj (+ (^ x 2) (- 2)) 2)

4. Conditional expressions with If

Build conditional terms with If(cond, then_val, else_val):

from apn_mojo import Integer
from z3_mojo import BoolVar, If, IntVar

var bonus = BoolVar("bonus", ctx)
var score = IntVar("score", ctx)
var s_if = Solver(ctx)
s_if.add(bonus, Eq(score, If(bonus, 100, 50)))
assert_equal(s_if.check(), sat)
assert_equal(s_if.model().get_integer(score).value(), Integer(100))

Try it yourself

  1. Add a fifth talk e in slots 1..5 that cannot be adjacent to Talk A, and use s.solutions to count how many valid schedules exist.
  2. Solve x^2 + y^2 == 1 with x == Rational(5, 13) and y < 0, and check that m.get_rational(y) returns -12/13.

Next: Part 2: Solver control — incremental solving, unsat cores, optimization, and tactics.

z3_mojo v5.3.3.0 for Mojo 1.2 and Z3 5.3.3 · Apache License 2.0 with LLVM Exceptions · Source on GitHub