Lesson goal: Symbolic Algebraic Simplification

Previous: Contest Counting: Digit String Constraints | Home | Next: The river crossing puzzle and AI search

When you use Computer Algebra Systems (CAS) like Wolfram Alpha, SymPy, or Mathematica, you can type expressions with unknown variables like $x \cdot 1 + 0$ and the computer immediately knows the answer is $x$.

How does the computer know this?

Unlike standard languages (like Lua, Python, or C) that try to calculate an immediate numerical value, a computer algebra system views math as a tree of symbols. It applies algebraic rewrite rules based on fundamental mathematical axioms:
  • Additive Identity: $X + 0 = X$ and $0 + X = X$
  • Multiplicative Identity: $X \cdot 1 = X$ and $1 \cdot X = X$
  • Zero Property of Multiplication: $X \cdot 0 = 0$ and $0 \cdot X = 0$
  • Constant Folding: If both operands are numbers, compute the arithmetic directly (e.g., $3 + 4 = 7$).
Because Prolog represents expressions like X + 0 as symbolic terms, we can build a working algebraic simplifier in just a few lines of logic!
simp(X + 0, X).
simp(0 + X, X).

simp(X * 1, X).

simp(X * 0, 0).

simp(A + B, Res) :- number(A), number(B), Res is A + B.

goal: simp(x * 1 + 0, Ans).
Move the mouse over a dotted box for more information.

  • Pattern Matching: In Prolog, X + 0 matches any expression whose top-level operator is + and whose right-hand operand is 0. The variable X binds to whatever is on the left side (even complex terms!).
  • Recursive Simplification: For compound expressions like $(x \cdot 1) + (y \cdot 0)$, we first simplify the sub-expressions, then simplify the combined result.

Now you try. Change the goal to simplify((5 + 3) * (w * 1 + 0), Ans). and hit Run.

Type your code here:


See your results here: