(sicp19)sicp問題2.56〜2.57
久しぶりに。
;;m.2.56 (define (deriv exp var) (cond ((number? exp) 0) ((variable? exp) (if (same-variable? exp var) 1 0)) ((sum? exp) (make-sum (deriv (addend exp) var) (deriv (augend exp) var))) ((product? exp) (make-sum (make-product (multiplier exp) (deriv (multiplicand exp) var)) (make-product (deriv (multiplier exp) var) (multiplicand exp)))) (else (error "unknown expression type -- DERIV" exp)))) (define (variable? e) (symbol? e)) (define (same-variable? v1 v2) (and (symbol? v1) (symbol? v2) (eq? v1 v2))) (define (make-sum a1 a2) (cond ((=number? a1 0) a2) ((=number? a2 0) a1) ((and (number? a1) (number? a2)) (+ a1 a2)) (else (list '+ a1 a2)))) (define (make-product m1 m2) (cond ((or (=number? m1 0) (=number? m2 0)) 0) ((=number? m1 1) m2) ((=number? m2 1) m1) ((and (number? m1) (number? m2)) (* m1 m2)) (else (list '* m1 m2)))) (define (=number? exp num) (and (number? exp) (= num exp))) (define (f? x symbol) (and (pair? x) (eq? (car x) symbol))) (define (sum? x) (f? x '+)) (define (product? x) (f? x '*)) (define (addend s) (cadr s)) (define (augend s) (caddr s)) (define (multiplier p) (cadr p)) (define (multiplicand p) (caddr p)) ;(deriv '(+ x 3) 'x) => 1 ;;m2.56---- (define (exponetiation? exp) (f? exp '**)) (define (base e) (cadr e)) (define (exponent e) (caddr e)) (define (make-exponetiation b e) (cond ((= e 0) 1) ((= e 1) b) (else (list '** b e)))) (define (deriv exp var) (cond ((number? exp) 0) ((variable? exp) (if (same-variable? exp var) 1 0)) ((sum? exp) (make-sum (deriv (addend exp) var) (deriv (augend exp) var))) ((product? exp) (make-sum (make-product (multiplier exp) (deriv (multiplicand exp) var)) (make-product (deriv (multiplier exp) var) (multiplicand exp)))) ((exponetiation? exp) (make-product (make-product (exponent exp) (make-exponetiation (base exp) (- (exponent exp) 1))) (deriv (base exp) var))) (else (error "unknown expression type -- DERIV" exp)))) (deriv '(** x 3) 'x) ;;gosh> (+ 3 (** n 2)) ;;m2.57 ;;残りの項を再帰的にということなので… (define (f g exp) (if (null? exp) 0 (g (car exp) (f g (cdr exp))))) (define (augend exp) (f make-sum (cddr exp))) (augend '(+ 1 2 3)) ;;5になってればいい ;;gosh> 5 (augend '(+ 2 3 4 x y 3 4)) ;;要素に文字が来ても ;;gosh> (+ 3 (+ 4 (+ x (+ y 7)))) ;;fってaccumulateだ。 ;;ということでこれだけで問題の回答になる。 (define (augend exp) (accumulate make-sum 0 (cddr exp))) (define (multiplicand exp) (accumulate make-product 1 (cddr exp))) (augend '(+ 1 2 3 4)) ;;gosh> 9 (multiplicand '(* 2 3 x 4 5)) ;;gosh> (* 3 (* x 20)) (deriv '(* x y (+ x 3)) 'x) ;;gosh> (+ (* x y) (* y (+ x 3)))
図形言語
何を使おう?
|