2008. 7. 30.

연습문제 2.57

여러 마디의 덧셈식과 곱셈식을 표현하려면 일단 make-sum과 make-product를 변형해야한다.

(define (make-sum . a)
  (append (list '+) a))

(define (make-product . s)
  (append (list '*) s))

이제 준식에 맞춰서 sum?, product?는 이전과 동일하다.

(define (sum? x)
  (and (pair? x) (eq? (car x) '+)))

(define (product? x)
  (and (pair? x) (eq? (car x) '*)))

이제 고르개를 바꾼다.

(define (length lst)
  (+ 0
     (cond ((null? lst) 0)
           ((pair? lst) (+ 1 (length (cdr lst))))
           (else 1))))

(define (augend s) (cadr s))

(define (addend s)
  (let ((sub_s (cddr s)))
    (cond ((> (length sub_s) 1) (cons '+ sub_s))
          (else (car sub_s)))))

(define (multiplicand p) (cadr p))

(define (multiplier p)
  (let ((sub_p (cddr p)))
    (cond ((> (length sub_p) 1) (cons '* sub_p))
          (else (car sub_p)))))

처럼 하면 된다.
이전 버전과는 달리.. 합치기 기능이 없어져서 답은 조금 산만하게 나온다.

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


댓글 없음:

댓글 쓰기