2.3.2 예제 수정

;; Differentiation
;; E := c | v | E + E | E * E — recurrence fomula

;; data definition = ctor + selector + predicate
(define (make-constant number) number)
(define (value constant) constant)
(define (constant? constant) (number? constant))
(define (same-constant? c1 c2) (and (constant? c1) (constant? c2) (eq? c1 c2)))

;; idioms
(define zero (make-constant 0))

(define (make-variable symbol) symbol)
(define (name variable) variable)
(define (variable? variable) (symbol? variable))
(define (same-variable? v1 v2) (and (variable? v1) (variable? v2) (eq? v1 v2)))

(define (=constant? e n) (and (constant? e) (= e n)))

(define (make-addexpr e1 e2)
(cond ((=constant? e1 0) e2)
((=constant? e2 0) e1)
((and (constant? e1) (constant? e2)) (make-constant (+ (value e1)
(value e2))))
(else (list ‘+ e1 e2))))
(define (addend e) (if (addexpr? e) (cadr e) (error “Not a Add Expr” e)))
(define (augend e) (if (addexpr? e) (caddr e) (error “Not a Add Expr” e)))
(define (addexpr? e) (eq? ‘+ (car e)))

(define (make-mulexpr e1 e2)
(cond ((or (=constant? e1 0) (=constant? e2 0)) zero)
((=constant? e1 1) e2)
((=constant? e2 1) e1)
((and (constant? e1) (constant? e2)) (make-constant (*S (value e1)
(value e2))))
(else (list ‘+ e1 e2))))
(define (multiplier e)
(if (mulexpr? e) (cadr e) (error “Not a Mul Expr” e)))
(define (multiplicand e)
(if (mulexpr? e) (caddr e) (error ” Not a Mul Expr” e)))
(define (mulexpr? e) (eq? ‘* (car e)))

(define (deriv e v) ;; explicit dispatch on types
(cond ((constant? e) zero)
((variable? e)
(if (same-variable? e v)
(make-constant 1)
zero))
((addexpr? e)
(make-addexpr (deriv (addend e) v)
(deriv (augend e) v)))
((mulexpr? e)
(make-addexpr
(make-mulexpr (multiplier e)
(deriv (multiplicand e) v))
(make-mulexpr (deriv (multiplier e) v)
(multiplicand e))))
(else
(error “Unknown type of expression” e))))

(deriv ‘(* (* x y) (+ x 3)) ‘x)

One thought on “2.3.2 예제 수정

  1. tandblekning

    Its such as you learn myy thoughts! You seem to
    understand so mjch approximately this, such as yyou wrote the ebook in it or something.
    I feel that you simply can do with some % to power the message house a little bit, but other than that, that is exzcellent blog.

    A great read. I will definitely be back.

Comments are closed.