;;---------------------------------------------------------------- ;;; -*- Mode: Lisp -*- ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; ;;; Copyright (C) 1999, 2002, 2009, 2015 Marek Rychlik ;;; ;;; This program is free software; you can redistribute it and/or modify ;;; it under the terms of the GNU General Public License as published by ;;; the Free Software Foundation; either version 2 of the License, or ;;; (at your option) any later version. ;;; ;;; This program is distributed in the hope that it will be useful, ;;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;;; GNU General Public License for more details. ;;; ;;; You should have received a copy of the GNU General Public License ;;; along with this program; if not, write to the Free Software ;;; Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. ;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defpackage "POLYNOMIAL" (:use :cl :utils :monom :copy :ring) (:export "POLY" "POLY-DIMENSION" "POLY-TERMLIST" "POLY-TERM-ORDER" "POLY-INSERT-TERM" "POLY-REMOVE-TERM" "SCALAR-MULTIPLY-BY" "SCALAR-DIVIDE-BY" "LEADING-TERM" "LEADING-MONOMIAL" "LEADING-COEFFICIENT" "SECOND-LEADING-TERM" "SECOND-LEADING-MONOMIAL" "SECOND-LEADING-COEFFICIENT" "ADD-TO" "ADD" "SUBTRACT-FROM" "SUBTRACT" "CHANGE-TERM-ORDER" "STANDARD-EXTENSION" "STANDARD-EXTENSION-1" "STANDARD-SUM" "SATURATION-EXTENSION" "ALIST->POLY" "POLY->ALIST" "->INFIX" "UNIVERSAL-EZGCD" "S-POLYNOMIAL" "POLY-CONTENT" "POLY-PRIMITIVE-PART" "SATURATION-EXTENSION-1" "MAKE-POLY-VARIABLE" "MAKE-POLY-CONSTANT" "MAKE-ZERO-FOR" "MAKE-UNIT-FOR" "UNIVERSAL-EXPT" "UNIVERSAL-EQUALP" "UNIVERSAL-ZEROP" "POLY-LENGTH" "POLY-REVERSE" "POLY-P" "+LIST-MARKER+" "POLY-EVAL" "*COEFFICIENT-CLASS*") (:documentation "Implements polynomials. A polynomial is essentially a mapping of monomials of the same degree to coefficients. The momomials are ordered according to a monomial order.")) (in-package :polynomial) (proclaim '(optimize (speed 3) (space 0) (safety 0) (debug 0))) (defclass poly (ring) ((termlist :initform nil :initarg :termlist :accessor poly-termlist :documentation "List of terms.") (order :initform #'lex> :initarg :order :accessor poly-term-order :documentation "Monomial/term order.")) (:default-initargs :termlist nil :order #'lex>) (:documentation "A polynomial with a list of terms TERMLIST, ordered according to term order ORDER, which defaults to LEX>.")) (defmethod print-object ((self poly) stream) (print-unreadable-object (self stream :type t :identity t) (with-accessors ((termlist poly-termlist) (order poly-term-order)) self (format stream "TERMLIST=~A ORDER=~A" termlist order)))) (defmethod copy-instance :around ((object poly) &rest initargs &key &allow-other-keys) "Returns a deep copy of the polynomial POLY, by copying the TERMLIST and its terms." (declare (ignore object initargs)) (let ((copy (call-next-method))) (with-slots (termlist) copy (setf termlist (mapcar #'copy-instance termlist))) copy)) (defgeneric change-term-order (self other) (:documentation "Change term order of SELF to the term order of OTHER.") (:method ((self poly) (other poly)) (unless (eq (poly-term-order self) (poly-term-order other)) (setf (poly-termlist self) (sort (poly-termlist self) (poly-term-order other)) (poly-term-order self) (poly-term-order other))) self)) (defgeneric poly-dimension (object) (:documentation "The number of variables in the polynomial OBJECT") (:method ((object poly)) (monom-dimension (leading-monomial object)))) (defgeneric poly-insert-term (self term) (:documentation "Insert a term TERM into SELF before all other terms. Order is not enforced.") (:method ((self poly) (term term)) (with-slots (termlist) self (unless (endp termlist) (assert (= (monom-dimension (car termlist)) (monom-dimension term))))) (push term (poly-termlist self)) self)) (defgeneric poly-remove-term (object) (:documentation "Remove leading term of polynomial OBJECT. Returns the removed term.") (:method ((object poly)) (pop (poly-termlist object)))) (defgeneric poly-append-term (self term) (:documentation "Append a term TERM to SELF after all other terms. Order is not enforced.") (:method ((self poly) (term term)) (with-slots (termlist) self (unless (endp termlist) (assert (= (monom-dimension (car termlist)) (monom-dimension term)))) (setf (cdr (last (poly-termlist self))) (list term))) self)) (defun alist->poly (alist &aux (poly (make-instance 'poly))) "It reads polynomial from an alist formatted as ( ... (exponents . coeff) ...). It can be used to enter simple polynomials by hand, e.g the polynomial in two variables, X and Y, given in standard notation as: 3*X^2*Y^3+2*Y+7 can be entered as (ALIST->POLY '(((0 0) . 7) ((0 1) . 2) ((2 3) . 3) )). NOTE: the terms are entered in the increasing order. NOTE: The primary use is for low-level debugging of the package." (dolist (x alist poly) (poly-insert-term poly (make-instance 'term :exponents (car x) :coeff (cdr x))))) (defun poly->alist (p) "Convert a polynomial P to an association list. Thus, the format of the returned value is ((MONOM[0] . COEFF[0]) (MONOM[1] . COEFF[1]) ...), where MONOM[I] is a list of exponents in the monomial and COEFF[I] is the corresponding coefficient in the ring." (cond ((poly-p p) (mapcar #'->list (poly-termlist p))) ((and (consp p) (eq (car p) :[)) (cons :[ (mapcar #'poly->alist (cdr p)))))) #+nil (defmethod shared-initialize :after ((self poly) slot-names &rest initargs &key) "If TERMLIST is supplied and non-empty, and DIMENSION is NIL, set the dimension to the dimension of the first term in TERMLIST." (declare (ignore initargs)) (let ((dims (mapcar #'monom-dimension (slot-value self 'termlist)))) (format t "Dimensions: ~A~%" dims) (assert (apply #'= dims)) (unless (endp dims) (setf (slot-value self 'dimension) (car dims)))) self) (defmethod update-instance-for-different-class :after ((old term) (new poly) &key) "Converts OLD of class TERM to a NEW of class POLY, by making it into a 1-element TERMLIST." (reinitialize-instance new :termlist (list old))) (defmethod update-instance-for-different-class :after ((old monom) (new poly) &key) "Converts OLD of class MONOM to a NEW of class POLY, by making it into a 1-element TERMLIST." (reinitialize-instance new :termlist (list (change-class old 'term)))) (defmethod universal-equalp ((self poly) (other poly)) "Implements equality of polynomials." (and ;(eql (poly-dimension self) (poly-dimension other)) (every #'universal-equalp (poly-termlist self) (poly-termlist other)) (eq (poly-term-order self) (poly-term-order other)))) (defgeneric leading-term (object) (:method ((self poly)) (car (poly-termlist self))) (:documentation "The leading term of a polynomial, or NIL for zero polynomial.")) (defgeneric second-leading-term (object) (:method ((self poly)) (cadar (poly-termlist self))) (:documentation "The second leading term of a polynomial, or NIL for a polynomial with at most one term.")) (defgeneric leading-monomial (object) (:method ((self poly)) (change-class (copy-instance (leading-term self)) 'monom)) (:documentation "The leading monomial of a polynomial, or NIL for zero polynomial.")) (defgeneric second-leading-monomial (object) (:method ((self poly)) (change-class (copy-instance (second-leading-term self)) 'monom)) (:documentation "The leading monomial of a polynomial, or NIL for zero polynomial.")) (defgeneric leading-coefficient (object) (:method ((self poly)) (term-coeff (leading-term self))) (:documentation "The leading coefficient of a polynomial. It signals error for a zero polynomial.")) (defgeneric second-leading-coefficient (object) (:method ((self poly)) (term-coeff (second-leading-term self))) (:documentation "The second leading coefficient of a polynomial. It signals error for a polynomial with at most one term.")) (defmethod universal-zerop ((self poly)) "Return T iff SELF is a zero polynomial." (null (poly-termlist self))) (defgeneric poly-length (self) (:documentation "Return the number of terms.") (:method ((self poly)) (length (poly-termlist self)))) (defgeneric scalar-multiply-by (self other) (:documentation "Multiply vector SELF by a scalar OTHER.") (:method ((self poly) other) (mapc #'(lambda (term) (setf (term-coeff term) (multiply-by (term-coeff term) other))) (poly-termlist self)) self)) (defgeneric scalar-divide-by (self other) (:documentation "Divide vector SELF by a scalar OTHER.") (:method ((self poly) other) (mapc #'(lambda (term) (setf (term-coeff term) (divide-by (term-coeff term) other))) (poly-termlist self)) self)) (defmethod unary-inverse :before ((self poly)) "Checks invertibility of a polynomial SELF. To be invertable, the polynomial must be an invertible, constant polynomial." (with-slots (termlist) self (assert (and (= (length termlist) 1) (zerop (total-degree (car termlist)))) nil "To be invertible, the polynomial must have 1 term of total degree 0."))) (defmethod unary-inverse ((self poly)) "Returns the unary inverse of a polynomial SELF." (with-slots (termlist) self (setf (car termlist) (unary-inverse (car termlist))) self)) (defmethod multiply-by ((self poly) (other monom)) "Multiply a polynomial SELF by OTHER." (mapc #'(lambda (term) (multiply-by term other)) (poly-termlist self)) self) (defmethod multiply-by ((self poly) (other term)) "Multiply a polynomial SELF by OTHER." (mapc #'(lambda (term) (multiply-by term other)) (poly-termlist self)) self) #| (defmacro fast-add/subtract (p q order-fn add/subtract-fn uminus-fn) "Return an expression which will efficiently adds/subtracts two polynomials, P and Q. The addition/subtraction of coefficients is performed by calling ADD/SUBTRACT-FN. If UMINUS-FN is supplied, it is used to negate the coefficients of Q which do not have a corresponding coefficient in P. The code implements an efficient algorithm to add two polynomials represented as sorted lists of terms. The code destroys both arguments, reusing the terms to build the result." `(macrolet ((lc (x) `(term-coeff (car ,x)))) (do ((p ,p) (q ,q) r) ((or (endp p) (endp q)) ;; NOTE: R contains the result in reverse order. Can it ;; be more efficient to produce the terms in correct order? (unless (endp q) ;; Upon subtraction, we must change the sign of ;; all coefficients in q ,@(when uminus-fn `((mapc #'(lambda (x) (setf x (funcall ,uminus-fn x))) q))) (setf r (nreconc r q))) (unless (endp p) (setf r (nreconc r p))) r) (multiple-value-bind (greater-p equal-p) (funcall ,order-fn (car p) (car q)) (cond (greater-p (rotatef (cdr p) r p) ) (equal-p (let ((s (funcall ,add/subtract-fn (lc p) (lc q)))) (cond ((universal-zerop s) (setf p (cdr p)) ) (t (setf (lc p) s) (rotatef (cdr p) r p)))) (setf q (cdr q)) ) (t ;;Negate the term of Q if UMINUS provided, signallig ;;that we are doing subtraction ,(when uminus-fn `(setf (lc q) (funcall ,uminus-fn (lc q)))) (rotatef (cdr q) r q)))) ;;(format t "P:~A~%" p) ;;(format t "Q:~A~%" q) ;;(format t "R:~A~%" r) ))) |# #| (defun fast-add (p q order-fn add-fn) "Add two polynomials, P and Q, represented as lists of terms. The operation is destructive to both polynomials, as the terms of both lists are combined into the result. The operation does not create any new instance of TERM." (macrolet ((lc (x) `(term-coeff (car ,x)))) (do (r) ((or (endp p) (endp q)) ;; NOTE: R contains the result in reverse order. Can it ;; be more efficient to produce the terms in correct order? (unless (endp q) (setf r (nreconc r q))) (unless (endp p) (setf r (nreconc r p))) r) (multiple-value-bind (greater-p equal-p) (funcall order-fn (car p) (car q)) (cond (greater-p (rotatef (cdr p) r p) ) (equal-p (let ((s (funcall add-fn (lc p) (lc q)))) (cond ((universal-zerop s) (setf p (cdr p)) ) (t (setf (lc p) s) (rotatef (cdr p) r p)))) (setf q (cdr q)) ) (t (rotatef (cdr q) r q))))))) |# ;; Getter/setter of leading coefficient (defun lc (x) (term-coeff (car x))) (defun (setf lc) (new-value x) (setf (term-coeff (car x)) new-value)) (defun slow-add (p q order-fn add-fn) (cond ((endp p) q) ((endp q) p) (t (multiple-value-bind (greater-p equal-p) (funcall order-fn (car p) (car q)) (cond (greater-p ; (> (car p) (car q)) (cons (car p) (slow-add (cdr p) q order-fn add-fn)) ) (equal-p ; (= (car p)) (car q)) (let ((s (funcall add-fn (lc p) (lc q)))) (cond ((universal-zerop s) (slow-add (cdr p) (cdr q) order-fn add-fn)) (t ;; Adjust the lc of p (setf (lc p) s) (cons (car p) (slow-add (cdr p) (cdr q) order-fn add-fn)) )))) (t ;(< (car p) (car q)) (cons (car q) (slow-add p (cdr q) order-fn add-fn)) )))))) (defun fast-and-risky-add (p q order-fn add-fn &aux result result-last) (when (and p q (eq p q)) (warn "FAST-AND-RISKY-ADD: ~S is EQ to ~S" p q)) (flet ((add-to-result (x) (assert (consp x)) (setf (cdr x) nil) (if (endp result) (setf result x result-last x) (setf (cdr result-last) x result-last (cdr result-last))))) (loop (cond ((endp p) (unless (endp q) (add-to-result q)) (return result)) ((endp q) (unless (endp p) (add-to-result p)) (return result)) (t (multiple-value-bind (greater-p equal-p) (funcall order-fn (car p) (car q)) (cond (greater-p ; (> (car p) (car q)) (let ((tmp (cdr p))) (add-to-result p) (setf p tmp))) (equal-p ; (= (car p)) (car q)) (let ((s (funcall add-fn (lc p) (lc q)))) (cond ((universal-zerop s) ;; Terms cancel, discard both (setf p (cdr p) q (cdr q))) (t ;; Terms do not cancel, store the ;; sum of coefficients in (lc p) (setf (lc p) s) (let ((tmp (cdr p))) (add-to-result p) (setf p tmp q (cdr q))))))) (t ;(< (car p) (car q)) (let ((tmp (cdr q))) (add-to-result q) (setf q tmp)) )))))))) (defun fast-add (p q order-fn add-fn) "This version calls SLOW-ADD and is bullet-proof." (slow-add p q order-fn add-fn) ;;(fast-and-risky-add p q order-fn add-fn) ) #| ;; NOTE: The stuff below works, but may not be worth the trouble. (defmacro def-add/subtract-method (add/subtract-method-name uminus-method-name &optional (doc-string nil doc-string-supplied-p)) "This macro avoids code duplication for two similar operations: ADD-TO and SUBTRACT-FROM." `(defmethod ,add/subtract-method-name ((self poly) (other poly)) ,@(when doc-string-supplied-p `(,doc-string)) ;; Ensure orders are compatible (change-term-order other self) (setf (poly-termlist self) (fast-add/subtract (poly-termlist self) (poly-termlist other) (poly-term-order self) #',add/subtract-method-name ,(when uminus-method-name `(function ,uminus-method-name)))) self)) (eval-when (:load-toplevel :execute) (def-add/subtract-method add-to nil "Adds to polynomial SELF another polynomial OTHER. This operation destructively modifies both polynomials. The result is stored in SELF. This implementation does no consing, entirely reusing the sells of SELF and OTHER.") (def-add/subtract-method subtract-from unary-minus "Subtracts from polynomial SELF another polynomial OTHER. This operation destructively modifies both polynomials. The result is stored in SELF. This implementation does no consing, entirely reusing the sells of SELF and OTHER.") ) |# (defmethod unary-minus ((self poly)) "Destructively modifies the coefficients of the polynomial SELF, by changing their sign." (mapc #'unary-minus (poly-termlist self)) self) (defun add-termlists (p q order-fn) "Destructively adds two termlists P and Q ordered according to ORDER-FN." (fast-add p q order-fn #'add-to)) (defun subtract-termlists (p q order-fn) "Destructively subtracts two termlists P and Q ordered according to ORDER-FN." (setf q (mapc #'unary-minus q)) (add-termlists p q order-fn)) (defmethod add-to ((self poly) (other poly)) "Adds to polynomial SELF another polynomial OTHER. This operation destructively modifies both polynomials. The result is stored in SELF. This implementation does no consing, entirely reusing the sells of SELF and OTHER." (change-term-order other self) (setf (poly-termlist self) (add-termlists (poly-termlist self) (poly-termlist other) (poly-term-order self))) self) (defmethod subtract-from ((self poly) (other poly)) "Subtracts from polynomial SELF another polynomial OTHER. This operation destructively modifies both polynomials. The result is stored in SELF. This implementation does no consing, entirely reusing the sells of SELF and OTHER." (change-term-order other self) (setf (poly-termlist self) (subtract-termlists (poly-termlist self) (poly-termlist other) (poly-term-order self))) self) (defmethod add-to ((self poly) (other term)) "Adds to a polynomial SELF a term OTHER. The term OTHER is not modified." (add-to self (change-class other 'poly))) (defmethod subtract-from ((self poly) (other term)) "Subtracts from a polynomial SELF a term OTHER. The term OTHER is not modified." (subtract-from self (change-class other 'poly))) (defmacro multiply-term-by-termlist-dropping-zeros (term termlist &optional (reverse-arg-order-P nil)) "Multiplies term TERM by a list of term, TERMLIST. Takes into accound divisors of zero in the ring, by deleting zero terms. Optionally, if REVERSE-ARG-ORDER-P is T, change the order of arguments; this may be important if we extend the package to non-commutative rings." `(mapcan #'(lambda (other-term) (let ((prod (multiply ,@(cond (reverse-arg-order-p `(other-term ,term)) (t `(,term other-term)))))) (cond ((universal-zerop prod) nil) (t (list prod))))) ,termlist)) (defun multiply-termlists (p q order-fn) "A version of polynomial multiplication, operating directly on termlists." (cond ((or (endp p) (endp q)) ;;p or q is 0 (represented by NIL) nil) ;; If p= p0+p1 and q=q0+q1 then p*q=p0*q0+p0*q1+p1*q ((endp (cdr p)) (multiply-term-by-termlist-dropping-zeros (car p) q)) ((endp (cdr q)) (multiply-term-by-termlist-dropping-zeros (car q) p t)) (t (cons (multiply (car p) (car q)) (add-termlists (multiply-term-by-termlist-dropping-zeros (car p) (cdr q)) (multiply-termlists (cdr p) q order-fn) order-fn))))) (defmethod multiply-by ((self poly) (other poly) &aux (other-copy (copy-instance other))) (change-term-order other-copy self) (setf (poly-termlist self) (multiply-termlists (poly-termlist self) (poly-termlist other-copy) (poly-term-order self))) self) (defmethod left-tensor-product-by ((self poly) (other monom)) (setf (poly-termlist self) (mapcan #'(lambda (term) (let ((prod (left-tensor-product-by term other))) (cond ((universal-zerop prod) nil) (t (list prod))))) (poly-termlist self))) self) (defmethod right-tensor-product-by ((self poly) (other monom)) (setf (poly-termlist self) (mapcan #'(lambda (term) (let ((prod (right-tensor-product-by term other))) (cond ((universal-zerop prod) nil) (t (list prod))))) (poly-termlist self))) self) (defun standard-extension (plist &aux (k (length plist)) (i 0)) "Calculate [U1*P1,U2*P2,...,UK*PK], where PLIST=[P1,P2,...,PK] is a list of polynomials. Destructively modifies PLIST elements." (mapc #'(lambda (poly) (left-tensor-product-by poly (prog1 (make-monom-variable k i) (incf i)))) plist)) (defun standard-extension-1 (plist &aux (plist (standard-extension plist)) (nvars (poly-dimension (car plist)))) "Calculate [U1*P1-1,U2*P2-1,...,UK*PK-1], where PLIST=[P1,P2,...,PK]. Firstly, new K variables U1, U2, ..., UK, are inserted into each polynomial. Subsequently, P1, P2, ..., PK are destructively modified tantamount to replacing PI with UI*PI-1. It assumes that all polynomials have the same dimension, and only the first polynomial is examined to determine this dimension." ;; Implementation note: we use STANDARD-EXTENSION and then subtract ;; 1 from each polynomial; since UI*PI has no constant term, ;; we just need to append the constant term at the end ;; of each termlist. (flet ((subtract-1 (p) (poly-append-term p (make-instance 'term :dimension nvars :coeff -1)))) (setf plist (mapc #'subtract-1 plist))) plist) (defun standard-sum (plist &aux (plist (standard-extension plist)) (nvars (poly-dimension (car plist)))) "Calculate the polynomial U1*P1+U2*P2+...+UK*PK-1, where PLIST=[P1,P2,...,PK]. Firstly, new K variables, U1, U2, ..., UK, are inserted into each polynomial. Subsequently, P1, P2, ..., PK are destructively modified tantamount to replacing PI with UI*PI, and the resulting polynomials are added. Finally, 1 is subtracted. It should be noted that the term order is not modified, which is equivalent to using a lexicographic order on the first K variables." (flet ((subtract-1 (p) (poly-append-term p (make-instance 'term :dimension nvars :coeff -1)))) (subtract-1 (make-instance 'poly :termlist (apply #'nconc (mapcar #'poly-termlist plist)))))) (defgeneric s-polynomial (object1 object2) (:documentation "Yields the S-polynomial of OBJECT1 and OBJECT2.") (:method ((f poly) (g poly)) (let* ((lcm (universal-lcm (leading-monomial f) (leading-monomial g))) (mf (divide lcm (leading-monomial f))) (mg (divide lcm (leading-monomial g)))) (multiple-value-bind (c cf cg) (universal-ezgcd (leading-coefficient f) (leading-coefficient g)) (declare (ignore c)) (subtract (multiply f mf cg) (multiply g mg cf)))))) (defgeneric poly-content (object) (:documentation "Greatest common divisor of the coefficients of the polynomial object OBJECT.") (:method ((self poly)) (reduce #'universal-gcd (mapcar #'term-coeff (rest (poly-termlist self))) :initial-value (leading-coefficient self)))) (defun poly-primitive-part (self) "Divide polynomial SELF by gcd of its coefficients. Return the resulting polynomial." (scalar-divide-by self (poly-content self))) (defun poly-insert-variables (self k) (left-tensor-product-by self (make-instance 'monom :dimension k))) (defun saturation-extension (f plist &aux (k (length plist))) "Calculate [F', U1*P1-1,U2*P2-1,...,UK*PK-1], where PLIST=[P1,P2,...,PK] and F' is F with variables U1,U2,...,UK inserted as first K variables. It destructively modifies F and PLIST." (nconc (mapc #'(lambda (x) (poly-insert-variables x k)) f) (standard-extension-1 plist))) (defun polysaturation-extension (f plist &aux (k (length plist))) "Calculate [F', U1*P1+U2*P2+...+UK*PK-1], where PLIST=[P1,P2,...,PK] and F' is F with variables U1,U2,...,UK inserted as first K variables. It destructively modifies F and PLIST." (nconc (mapc #'(lambda (x) (poly-insert-variables x k)) f) (list (standard-sum plist)))) (defun saturation-extension-1 (f p) "Given family of polynomials F and a polynomial P, calculate [F', U*P-1], where F' is F with variable inserted as the first variable. It destructively modifies F and P." (polysaturation-extension f (list p))) (defmethod multiply-by ((self poly) (other ring)) (scalar-multiply-by self other)) (defun make-poly-variable (nvars pos &optional (power 1)) (change-class (make-monom-variable nvars pos power) 'poly)) (defun make-poly-constant (nvars coeff) (change-class (make-term-constant nvars coeff) 'poly)) (defgeneric universal-expt (x y) (:documentation "Raises X to power Y.") (:method ((x number) (y integer)) (expt x y)) (:method ((x t) (y integer)) (declare (type fixnum y)) (cond ((minusp y) (error "universal-expt: Negative exponent.")) ((universal-zerop x) (if (zerop y) 1)) (t (do ((k 1 (ash k 1)) (q x (multiply q q)) ;keep squaring (p (make-unit-for x) (if (not (zerop (logand k y))) (multiply p q) p))) ((> k y) p) (declare (fixnum k))))))) (defgeneric poly-p (object) (:documentation "Checks if an object is a polynomial.") (:method ((self poly)) t) (:method ((self t)) nil)) (defmethod ->sexp :before ((self poly) &optional vars) "Ensures that the number of variables in VARS maches the polynomial dimension of the polynomial SELF." (let ((dimension (poly-dimension self))) (assert (= (length vars) dimension) nil "Number of variables ~S does not match the dimension ~S" vars dimension))) (defmethod ->sexp ((self poly) &optional vars) "Converts a polynomial SELF to a sexp." (let ((m (mapcar #'(lambda (trm) (->sexp trm vars)) (poly-termlist self)))) (cond ((endp m) 0) ((endp (cdr m)) (car m)) (t (cons '+ m))))) (defconstant +list-marker+ :[ "A sexp with this head is considered a list of polynomials.") (defmethod ->sexp ((self cons) &optional vars) (assert (eql (car self) +list-marker+)) (cons +list-marker+ (mapcar #'(lambda (p) (->sexp p vars)) (cdr self)))) (defmethod make-zero-for ((self poly)) (make-instance 'poly)) (defmethod make-unit-for ((self poly)) (make-poly-constant (poly-dimension self) 1)) (defgeneric poly-reverse (self) (:documentation "Reverse the order of terms in a polynomial SELF.") (:method ((self poly)) (with-slots (termlist) self (setf termlist (nreverse termlist))) self))