1 | (in-package "POLYNOMIAL")
|
---|
2 |
|
---|
3 | (defun fast-and-risky-add (p q order-fn add-fn &aux result result-last)
|
---|
4 | (when (and p q (eq p q)) (warn "FAST-AND-RISKY-ADD: ~S is EQ to ~S" p q))
|
---|
5 | (flet ((add-to-result (x)
|
---|
6 | (assert (consp x))
|
---|
7 | (setf (cdr x) nil)
|
---|
8 | (if (endp result)
|
---|
9 | (setf result x
|
---|
10 | result-last x)
|
---|
11 | (setf (cdr result-last) x
|
---|
12 | result-last (cdr result-last)))))
|
---|
13 | (loop
|
---|
14 | (format t "RESULT: ~S~%" (mapcar #'->list result))
|
---|
15 | (format t "RESULT-LAST: ~S~%" (mapcar #'->list result-last))
|
---|
16 | (format t "P: ~S~%" (mapcar #'->list p))
|
---|
17 | (format t "Q: ~S~%" (mapcar #'->list q))
|
---|
18 | (cond
|
---|
19 | ((endp p) (unless (endp q) (add-to-result q)) (return result))
|
---|
20 | ((endp q) (unless (endp p) (add-to-result p)) (return result))
|
---|
21 | (t
|
---|
22 | (multiple-value-bind
|
---|
23 | (greater-p equal-p)
|
---|
24 | (funcall order-fn (car p) (car q))
|
---|
25 | (cond
|
---|
26 | (greater-p ; (> (car p) (car q))
|
---|
27 | (let ((tmp (cdr p)))
|
---|
28 | (add-to-result p)
|
---|
29 | (setf p tmp)))
|
---|
30 | (equal-p ; (= (car p)) (car q))
|
---|
31 | (let ((s (funcall add-fn (lc p) (lc q))))
|
---|
32 | (cond
|
---|
33 | ((universal-zerop s)
|
---|
34 | ;; Terms cancel, discard both
|
---|
35 | (setf p (cdr p)
|
---|
36 | q (cdr q)))
|
---|
37 | (t
|
---|
38 | ;; Terms do not cancel, store the
|
---|
39 | ;; sum of coefficients in (lc p)
|
---|
40 | (setf (lc p) s)
|
---|
41 | (let ((tmp (cdr p)))
|
---|
42 | (add-to-result p)
|
---|
43 | (setf p tmp
|
---|
44 | q (cdr q)))))))
|
---|
45 | (t ;(< (car p) (car q))
|
---|
46 | (let ((tmp (cdr q)))
|
---|
47 | (add-to-result q)
|
---|
48 | (setf q tmp))
|
---|
49 | ))))))))
|
---|
50 |
|
---|
51 | (defun fast-add (p q order-fn add-fn)
|
---|
52 | (let ((r1 (slow-add p q order-fn add-fn))
|
---|
53 | (r2 (fast-and-risky-add p q order-fn add-fn)))
|
---|
54 | (unless (every #'universal-equalp r1 r2)
|
---|
55 | (format t "~&Error in addition of ~%~A~% and~%~A~% should be:~%" (mapcar #'->list p) (mapcar #'->list q))
|
---|
56 | (princ (mapcar #'->list r1))
|
---|
57 | (format t "~&Actually is:~%")
|
---|
58 | (princ (mapcar #'->list r2))
|
---|
59 | )
|
---|
60 | r2))
|
---|
61 |
|
---|
62 |
|
---|
63 |
|
---|