SICP学习笔记 2.3.2 实例:符号求导
程序员文章站
2022-05-28 21:41:58
...
练习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)))) ((exponentiation? exp) (make-product (make-product (exponent exp) (make-exponentiation (base exp) (- (exponent exp) 1))) (deriv (base exp) var))) (else (error "unknown expression type -- DERIV" exp))))
练习2.57
;; 加法 (define (make-sum-list x list) (if (null? list) x (make-sum x (make-sum-list (car list) (cdr list))))) (define (make-sum-all x . y) (make-sum-list x y)) ;; 被加数 (define (augend-list s) (let ((l (length s))) (cond ((= l 1) 0) ((= l 2) (cadr s)) ((= l 3) (augend s)) (else (cons '+ (cddr s)))))) ;; 乘法 (define (make-product-list x list) (if (null? list) x (make-product x (make-product-list (car list) (cdr list))))) (define (make-product-all x . y) (make-product-list x y)) ;; 被乘数 (define (multiplicand-list p) (let ((l (length p))) (cond ((= l 1) 1) ((= l 2) (cadr p)) ((= l 3) (multiplicand p)) (else (cons '* (cddr p)))))) ;; 使用新的加法和乘法构造求导过程 (define (deriv exp var) (cond ((number? exp) 0) ((variable? exp) (if (same-variable? exp var) 1 0)) ((sum? exp) (make-sum-all (deriv (addend exp) var) (deriv (augend-list exp) var))) ((product? exp) (make-sum-all (make-product-all (multiplier exp) (deriv (multiplicand-list exp) var)) (make-product-all (deriv (multiplier exp) var) (multiplicand-list exp)))) ((exponentiation? exp) (make-product-all (make-product-all (exponent exp) (make-exponentiation (base exp) (- (exponent exp) 1))) (deriv (base exp) var))) (else (error "unknown expression type -- DERIV" exp)))) 1 ]=> (deriv '(* x y (+ x 3)) 'x) ;Value : (+ (* x y) (* y (+ x 3)))
练习2.58
;; 修改加法的构造函数、选择函数和谓词 (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)))) (else (list a1 '+ a2)))) (define (addend s) (car s)) (define (augend s) (caddr s)) (define (sum? x) (and (pair? x) (eq? (cadr x) '+)) ;; 使用类似的方法修改乘法的构造函数、选择函数和谓词 1 ]=> (deriv '((x * y) * ( x + 3)) 'x) ;Value : ((x * y) + (y * (x + 3))) 1 ]=> (deriv '(x + (3 * (x + (y + 2)))) 'x) ;Value: 4
练习2.59
;; 暂无