SICP

it2024-11-13  14

#lang racket ;;;;;;;;;;;;;;;只需先写出按愿望和公式而构造的函数 ;;;;;;;;;;;;;;;再加上一些特定的选择函数和构造函数就可以实现这么强大的功能 ;;;;;;;;;;;;;;;quote 和 list 的区别 (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 "unknow expression type --DERIV" exp)))) (define (variable? x) (symbol? x)) (define (same-variable? v1 v2) (and (variable? v1) (variable? v2) (eq? v1 v2))) (define (=number? exp num) (and (number? exp) (= exp num))) (define (** a b) (define (iter n result) (cond ((= 0 b) 1) ((or (< n b) (= n b)) (iter (+ n 1) (* a result))) ((> n b) result))) (iter 1 1)) (define (sum? x) (and (pair? x) (eq? (car x) '+))) ;(define (addend s) (cadr s)) ;(define (augend s) (caddr s)) (define (product? x) (and (pair? x) (eq? (car x) '*))) ;(define (multiplier p) (cadr p)) ;(define (multiplicand p) (caddr p)) (define (exponentiation? x) (and (pair? x) (eq? (car x) '**))) (define (base e) (cadr e)) (define (exponent e) (caddr e)) (define (make-exponentiation b1 b2) (cond ((=number? b2 0) 1) ((=number? b2 1) b1) ((and (number? b1) (number? b2)) (** b1 b2)) (else (list '** b1 b2)))) (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)))) ;;;;;;;;;;;;test ;(deriv '(* (* x y) (+ x 3)) 'x) ;(deriv '(** (+ x y) 4) 'x) ;(deriv '(+ (* x y) x) 'x) ;;;;;;;;;;;;;2.58 (define (addend s) (cadr s)) (define (augend s) (if (null? (cdddr s)) (caddr s) (cons '+ (cddr s)))) (define (multiplier p) (cadr p)) (define (multiplicand p) (if (null? (cdddr p)) (caddr p) (cons '* (cddr p)))) ;;;;;;;;;;;;test (deriv '(+ (* x 4) (+ x x) (* x x)) 'x) (deriv '(* (+ x 4) (* x 4) y (** x 3)) 'y)

 

1.这几题进一步强化了按愿望实现函数的方法

 

2.quoto 和 list 的区别  参考

 

(1)' 是quoto 的缩写

 

(2)' 后的内容会原样返回,因为 ' 就是个省略了的单引号 

(= '3 3)    ->#t

(car  '(list a b))   ->list    (和sicp_2.55同理)

 

(3)list 是个函数

(list (+ 1 3) (+ 2 5)) -> (4 7)

转载于:https://www.cnblogs.com/tclan126/p/6443803.html

相关资源:数据结构—成绩单生成器
最新回复(0)