[2021 Spring] CS61A Discussion 11: Interpreters
Disc 11:https://inst.eecs.berkeley.edu/~cs61a/sp21/disc/disc11/
目录
Evaluation
跟Lab 11的思路是一样的:
Scheme Lists
Q6: (Tutorial) Replicate
递归
(define (replicate x n)
(if (= n 0)
nil
(cons x (replicate x (- n 1))))
)
;;; Tests
(replicate 5 3)
; expect (5 5 5)
Q7: (Tutorial) Run Length Encoding
需要用到replicate和my-append。
(define (my-append a b)
(if (null? a)
b
(cons (car a) (my-append (cdr a) b))))
(define (uncompress s)
(if (null? s)
nil
(my-append (replicate (car (car s)) (car (cdr (car s)))) (uncompress (cdr s))))
)
;;; Tests
(uncompress '((a 1) (b 2) (c 3)))
; expect (a b b c c c)
Q8: (Tutorial) Map
(define (map fn lst)
(if (null? lst)
nil
(cons (fn (car lst)) (map fn (cdr lst))))
)
;;; Tests
(map (lambda (x) (* x x)) '(1 2 3))
; expect (1 4 9)
Q9: (Tutorial) Make Tree
(define (make-tree label branches) (cons label branches))
(define (label tree)
(car tree)
)
(define (branches tree)
(cdr tree)
)
Q10: (Tutorial) Tree Sum
(define (tree-sum tree)
(+ (label tree) (sum (map tree-sum (branches tree))))
)
(define (sum lst)
(if (null? lst)
0
(+ (car lst) (sum (cdr lst)))))