We define a method on equal so we can check if two polynomials are the same. Notice we do not have to check for the bottoming-out of the recursion on the reducta: the generic nature of equal ensures that when we get to the end of a polynomial (and we have an integer as a reductum rather than a polynomial) a different method is called. This relies on the fact that equal-methods for (int, poly) and (poly, int) do not exist: the generic function discriminator chooses the nearest applicable method on equal, which in this case is (object, object). This method returns () (as the args cannot be eq), which is just what we want.
(defmethod equal ((p <polynomial>) (q <polynomial>)) (and (equal (ldeg p) (ldeg q)) (equal (lc p) (lc q)) (equal (red p) (red q))))
We now need some operations on this new type. If we are trying to add polynomials to integers, we would like some method for converting between integers and polynomials. We use the function lift-numbers to do this. (defmethod lift-numbers ((i <integer>) (p <polynomial>)) <polynomial>)
(defmethod lift-numbers ((p <polynomial>) (i <integer>)) <polynomial>)
(defmethod (converter <polynomial>) ((x <integer>)) (make-polynomial 'lc x 'ldeg 0)) Now if we call any operation with a polynomial and an integer, the integer is lifted to class polynomial, and the operation proceeds as normal. For two polynomials, the method is easy. A minor wrinkle is when the leading terms cancel: we must take care not to have a leading coefficient of 0. (defmethod binary-plus ((p <polynomial>) (q <polynomial>)) (cond ((= (ldeg p) (ldeg q)) (let ((sum (binary-plus (lc p) (lc q)))) (if (zerop sum) (binary-plus (red p) (red q)) (make-polynomial 'ldeg (ldeg p) 'lc sum 'red (binary-plus (red p) (red q)))))) ((< (ldeg p) (ldeg q)) (make-polynomial 'ldeg (ldeg q) 'lc (lc q) 'red (binary-plus p (red q)))) (t (make-polynomial 'ldeg (ldeg p) 'lc (lc p) 'red (binary-plus (red p) q)))))
(defmethod binary-difference ... and so on for the other arithmetic operations. Also we would put new methods on generic-prin and generic-write to print out the values of polynomials using a suitable syntax.