乐正

Actions speak louder than words.

Sicp-ex2-57

问题

请扩充求导程序,使之能处理任意项(两项或者更多项)的和与乘积。这样上面的最后一个 例子就可以表示为:

1
(deriv '(* x y (+ x 3)) 'x)

设法通过值修改和与乘积的表示,而完全不修改过程deriv的方式完成这一扩充。例如: 让一个和式的addend是它的第一项,而其augend是和式中的其余项。

解答

练习2.57 (ex2-57.scm) download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
(define (augend s)
  (if (> (length s) 3)
      (cons '+ (cddr s))
      (caddr s)))

(define (make-sum a1 . an)
  (if (=number? (length an) 1)
    (let ((a2 (car an)))
      (cond ((=number? a1 0) a2)
            ((=number? a2 0) a1)
            ((and (number? a1) (number? a2)) (+ a1 a2))
            (else (list '+ a1 a2))))
    (cons '+ (cons a1 an))))

(define (multiplicand p)
  (if (> (length p) 3)
      (cons '* (cddr p))
      (caddr p)))

(define (make-product m1 . mn)
  (if (=number? (length mn) 1)
    (let ((m2 (car mn)))
      (cond ((or (=number? m1 0) (=number? m2 0)) 0)
            ((=number? m1 1) m2)
            ((=number? m2 2) m1)
            ((and (number? m1) (number? m2)) (* m1 m2))
            (else (list '* m1 m2))))
    (cons '* (cons m1 mn))))

测试

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
;; (load sicp/ex2-56.scm)
;; (load sicp/ex2-57.scm)

(make-product 3 4)
;Value: 12

(make-product 'x 'y 'z)
;Value 14: (* x y z)

(multiplicand (list '* 'x 'y 'z))
;Value 15: (* y z)

(make-sum 'x 'y 3)
;Value 16: (+ x y 3)

(make-sum 3 4)
;Value: 7

(augend (make-sum 'x 'y 3))
;Value 17: (+ y 3)

(deriv '(* x y (+ x 3)) 'x)
;Value 18: (+ (* x (* y 1)) (* y (+ x 3)))

draft

« sicp-ex2-56 sicp-ex2-58 »

Comments