[2021 Spring] CS61A 学习笔记 Homework 8: More Scheme

作业说明:https://inst.eecs.berkeley.edu/~cs61a/sp21/hw/hw08/

Q1: WWSD: Quasiquote

注意点: ','后的expr会被eval, ',@'后的expr eval后spliced in.

Q2: Tail Recursive Accumulate

将hw07中的accumulate修改为tail-recursive。其实写hw07的时候已经是tail-recursive了,直接用就行。

(define (accumulate-tail combiner start n term)
    (if (< n 1) start
        (accumulate-tail combiner (combiner start (term n)) (- n 1) term)))

Q3: Derive Sum

derive返回EXPR对VAR的导数,按照求导法则写出代码。
\((f(x) + g(x))' = f'(x) + g'(x)\)

(define (derive-sum expr var) 
    (make-sum (derive (first-operand expr) var) 
              (derive (second-operand expr) var)))

Q4: Derive Product

\((f(x) g(x))' = f'(x) g(x) + f(x) g'(x)\)

(define (derive-product expr var) 
    (make-sum (make-product (derive (first-operand expr) var)
                            (second-operand expr))
              (make-product (first-operand expr)
                            (derive (second-operand expr) var))))

Q5: Make Exp

reformat优化格式

; Exponentiations are represented as lists that start with ^.
(define (make-exp base exponent)
  (cond 
    ((=number? exponent 0)
     1)
    ((=number? exponent 1)
     base)
    ((and (number? base) (number? exponent))
     (expt base exponent))
    (else
     (list '^ base exponent))))

(define (exp? exp)
  (and (list? exp) (eqv? (car exp) '^)))

Q6: Derive Exp

\([f(x)^{g(x)}]' = f(x)^{g(x) - 1} * g(x)\)
注意点:make-product的顺序

(define (derive-exp exp var)
  (make-product (second-operand exp)
                (make-exp (first-operand exp)
                          (- (second-operand exp) 1))))
posted @ 2021-08-04 21:41  ikventure  阅读(1014)  评论(0编辑  收藏  举报