SICP 全笔记

Exercise 2.87. Install =zero? for polynomials in the generic arithmetic package. This will allow adjoin-term to work for polynomials with coefficients that are themselves polynomials.

实现了 =zero? 之后,我们就能对系数也是多项式的多项式进行加减了。

建立在 练习 2.84 上,我们实现一个判断一个多项式是否为 0 的过程:

  (define (zero-polynomial? p)
    (define (zero-terms? ts)
      (cond ((empty-termlist? ts) true)
            ((=zero? (coeff (first-term ts)))
             (zero-terms? (rest-terms ts)))
            (else false)))
    (zero-terms? (term-list p)))

然后使用 put 把写好的 zero-polynomial? 过程加到 =zero? 里面。

下面是测试:

(load "../testframe.scm")

(asserttrue (=zero? (make-polynomial 'x '((100 0) (2 0) (0 0)))))

(asserteq? false (=zero? (make-polynomial 'x '((100 0) (2 0) (0 1)))))

(assertequal? (add (make-polynomial 'x '((100 1) (2 2) (0 1)))
                   (make-polynomial 'x '((100 1) (2 2) (0 1))))
              (make-polynomial 'x '((100 2) (2 4) (0 2))))

; mul requires the raise (or drop) implemented in 2.84 or 2.85.

;; (mul (make-polynomial 'x
;;                       (list (list 2 3)
;;                             (list 1 (make-complex-from-real-imag 2 3))
;;                             (list 0 7)))
;;      (make-polynomial 'x
;;                       (list (list 4 1)
;;                             (list 2 (make-rational 2 3))
;;                             (list 0 (make-complex-from-real-imag 5 3)))))

; [(y^3+4)x^2 + (y+3)x] + [(2y^3 + 5)x^2]
; = [(3y^3+9)x^2 + (y+3)x + 1
(assertequal? (add (make-polynomial
                    'x
                    (list (list 2 (make-polynomial 'y '((3 1) (0 4))))
                          (list 1 (make-polynomial 'y '((1 1) (0 3))))))
                   (make-polynomial
                    'x
                    (list (list 2 (make-polynomial 'y '((3 2) (0 5)))))))
              (make-polynomial
               'x
               (list (list 2 (make-polynomial 'y '((3 3) (0 9))))
                     (list 1 (make-polynomial 'y '((1 1) (0 3)))))))