Symbolic polynomial math
File: symbolic-math.lisp
A small computer-algebra system: polynomials as association lists, exact rational arithmetic (addition, subtraction, multiplication), derivatives, integrals, and definite integrals by the fundamental theorem of calculus.
The program stores a polynomial as a sorted alist of (exponent . coefficient) pairs with like terms combined and zeros dropped, so
is ((2 . 3) (1 . -1) (0 . 5)). The calculus is the power rule in both directions:

and a definite integral evaluates the antiderivative at the endpoints:

The code
1 ;; sbcl --script symbolic-math.lisp (symbolic polynomial calculus)
2 ;;;; Polynomials are alists ((exponent . coefficient) ...):
3 ;;;; descending exponents, like terms combined, zeros dropped.
4 ;;;; 3x^2 - x + 5 = ((2 . 3) (1 . -1) (0 . 5))
5
6 (defun normalize (terms)
7 (let ((h (make-hash-table)))
8 (loop for (e . c) in terms do (incf (gethash e h 0) c))
9 (sort (loop for e being the hash-keys of h using (hash-value c)
10 unless (zerop c) collect (cons e c))
11 #'> :key #'car)))
12
13 (defun poly (&rest coefs) ; (poly 3 -1 5) => 3x^2 - x + 5
14 (normalize
15 (loop for c in (reverse coefs) for e from 0 collect (cons e c))))
16
17 ;;; Arithmetic & evaluation
18 (defun p+ (&rest ps) (normalize (apply #'append ps)))
19 (defun scale (p k)
20 (normalize (loop for (e . c) in p collect (cons e (* k c)))))
21 (defun p- (p q) (p+ p (scale q -1)))
22 (defun p* (p q) ; every term times every term
23 (normalize (loop for (e1 . c1) in p
24 append (loop for (e2 . c2) in q
25 collect (cons (+ e1 e2) (* c1 c2))))))
26 (defun degree (p) (if p (caar p) -1))
27 (defun evaluate (p x) (loop for (e . c) in p sum (* c (expt x e))))
28
29 ;;; Calculus: power rule, reverse power rule, fundamental theorem
30 (defun deriv (p &optional (n 1))
31 (if (zerop n) p
32 (deriv
33 (loop for (e . c) in p
34 unless (zerop e)
35 collect (cons (1- e) (* e c)))
36 (1- n))))
37
38 (defun integ (p &optional (n 1))
39 (if (zerop n) p
40 (integ
41 (loop for (e . c) in p
42 collect (cons (1+ e) (/ c (1+ e))))
43 (1- n))))
44
45 (defun bound (b) ; rationals stay exact
46 (case b
47 (:pi pi)
48 (:e (exp 1d0))
49 (t (if (rationalp b) b (float b 1d0)))))
50
51 (defun definite (p a b)
52 (let ((f (integ p)))
53 (- (evaluate f (bound b)) (evaluate f (bound a)))))
54
55 (defun critical-point-p (p x &optional (tol 1d-9))
56 (< (abs (evaluate (deriv p) x)) tol))
57
58 ;;; Display
59 (defun term->string (e c v) ; magnitude only: 3x^2, x, 5
60 (let ((m (abs c)))
61 (format nil "~:[~a~;~*~]~@[~(~a~)~]~@[^~a~]"
62 (and (= m 1) (> e 0)) m ; hide a coefficient of 1
63 (and (> e 0) v)
64 (and (> e 1) e))))
65
66 (defun ->string (p &optional (v 'x))
67 (if (null p) "0"
68 (with-output-to-string (out)
69 (loop for (e . c) in p
70 for first = t then nil
71 do (write-string (cond ((not first)
72 (if (minusp c) " - " " + "))
73 ((minusp c) "-")
74 (t ""))
75 out)
76 (write-string (term->string e c v) out)))))
77
78 (defun integral->string (p &optional a b (v 'x))
79 (flet ((show (limit) (case limit (:pi "π") (:e "e") (t limit))))
80 (format nil "∫~@[[~{~a~^,~}]~](~a) d~(~a~)"
81 (and a (list (show a) (show b)))
82 (->string p v)
83 v)))
84
85 ;;; Examples
86 (let ((p (poly 3 -1 5)) ; 3x^2 - x + 5
87 (q (poly 1 2))) ; x + 2
88 (format t "p : ~a~%" (->string p))
89 (format t "p + q : ~a~%" (->string (p+ p q)))
90 (format t "p - q : ~a~%" (->string (p- p q)))
91 (format t "p * q : ~a~%" (->string (p* p q)))
92 (format t "2p : ~a~%" (->string (scale p 2)))
93 (format t "degree, p(2): ~a, ~a~%" (degree p) (evaluate p 2))
94 (format t "p', p'', p''': ~a | ~a | ~a~%"
95 (->string (deriv p))
96 (->string (deriv p 2))
97 (->string (deriv p 3)))
98 (format t "∫p, ∫∫p : ~a | ~a~%"
99 (->string (integ p))
100 (->string (integ p 2)))
101 (format t "~a = ~a~%" (integral->string p 0 1) (definite p 0 1))
102 (format t "~a = ~,4f~%" (integral->string p 0 :pi) (definite p 0 :pi))
103 (format t "x=1/6 critical? ~a x=0? ~a~%"
104 (critical-point-p p 1/6)
105 (critical-point-p p 0)))
How it works
normalizekeeps polynomials in canonical form: it sums coefficients per exponent in a hash table, drops zero coefficients, and sorts by descending exponent. Every constructor and arithmetic function calls it.polybuilds a polynomial from coefficients highest-degree first:(poly 3 -1 5)means
.
p*multiplies every term of one polynomial by every term of the other (add exponents, multiply coefficients) and letsnormalizecombine like terms. The canonical form keeps multiplication down to three lines.- Coefficients are ordinary Lisp numbers, so ratios stay exact. The antiderivative of
has coefficient
, but the antiderivative of
carries the rational
.
derivandintegtake an optional repeat count:(deriv p 3)is the third derivative, computed by recursing on the single-step rule. Theunless (zerop e)clause drops the constant term underderiv.boundaccepts integration bounds as numbers or the keywords:piand:e. Rational bounds (integers and ratios) stay exact, so(definite p 0 1)returns the exact rational11/2; only:pi,:e, and float bounds produce a double float.critical-point-pchecks whether
within a tolerance. For our quadratic,
at
, and since 1/6is an exact rational, the derivative evaluates to exactly zero.->stringprints polynomials the way people write them:3x^2 - x + 5, not3x^2 + -1x + 5.term->stringprints one term’s magnitude and hides a coefficient of 1 on non-constant terms;->stringadds the signs: a leading-for a negative first term, then+or-between terms. Theformatdirective~:[...~;...~]picks one of two clauses based on a boolean, and~@[...~]prints a group only when its argument is non-nil, which is how the variable and exponent appear only when needed.
Running it
1 $ sbcl --script symbolic-math.lisp
Actual output:
1 p : 3x^2 - x + 5
2 p + q : 3x^2 + 7
3 p - q : 3x^2 - 2x + 3
4 p * q : 3x^3 + 5x^2 + 3x + 10
5 2p : 6x^2 - 2x + 10
6 degree, p(2): 2, 15
7 p', p'', p''': 6x - 1 | 6 | 0
8 ∫p, ∫∫p : x^3 - 1/2x^2 + 5x | 1/4x^4 - 1/6x^3 + 5/2x^2
9 ∫[0,1](3x^2 - x + 5) dx = 11/2
10 ∫[0,π](3x^2 - x + 5) dx = 41.7794
11 x=1/6 critical? T x=0? NIL
Check the ninth line against the symbolic answer:

The program agrees exactly: 11/2 is a Lisp ratio, not a rounded 5.5. Arithmetic stays rational from the antiderivative (-1/2x^2, 5/2x^2 in the output) to the answer. Only the integral up to :pi needs floating point, because
is irrational.
Using it
Use it to check calculus homework, generate exact examples for teaching, or as the symbolic core of a larger system. Natural extensions: polynomial long division (which pairs well with p*), composition
built from p* and p+, rational functions as pairs of polynomials, or a solve for quadratic roots. The choice of representation (canonical alists) keeps every operation short, and it deserves as much study as the calculus.