[2021 spring] CS61A Lab 12: Tail Recursion, Scheme

Lab 12: https://inst.eecs.berkeley.edu/~cs61a/sp21/lab/lab12/

Q2: Replicate

scheme的tail-recursion比python快得多,需要辅助函数

(define (tail-replicate x n)
    (define (tail-replicate-optimize x n so-far)
        (if (= n 0)
            so-far
            (tail-replicate-optimize x (- n 1) (cons x so-far))))
    (tail-replicate-optimize x n nil))

Q3: Scheme def

(define-macro (def func args body)
  `(define ,func (lambda ,args ,body)))
# or
(define-macro (def func args body)
  `(define (,func ,@args) ,body))

Q4: Repeatedly Cube

利用递归进行重复立方

(define (repeatedly-cube n x)
  (if (zero? n)
      x
      (let ((y (repeatedly-cube (- n 1) x)))
        (* y y y))))
posted @ 2021-08-05 12:25  ikventure  阅读(1292)  评论(0编辑  收藏  举报