Computer Science 61A: Structure and Interpretation

advertisement

Computer Science 61A Study Group

Student Learning Center

Leader: Joo-Rak Son

Week 15, December 6 th and 8 th

1. Object-Oriented Programming

(define (make-echo saved)

(let ((count 0))

(lambda (message)

(cond ((eq? message ‘saved) saved)

((eq? message ‘count) count)

(else (let ((result saved))

(set! saved message)

(set! count (+ count 1))

result))))))

2. Data Abstraction and Higher-Order Functions

(a)

(define (prefix-to-infix exp)

(if (pair? exp)

(list (prefix-to-infix (cadr exp))

(prefix-to-infix (car exp))

(prefix-to-infix (caddr exp)))

(list (cadr exp) (car exp) (caddr exp))))

(b)

(define (tree-reorder ordering tree)

(if (atom? tree)

tree

(map (lambda (index)

(tree-reorder ordering (list-ref tree index)))

ordering)))

3. Logic Programming

(a)

! (assq ?key ((?key . ?value) . ?tail) (?key . ?value)) . [I]

! (assq ?key (?irrelevant . ?tail) ?result) :- [II]

(assq ?key ?tail ?result) .

(b)

___ (assq bbb ((aaa . 5) (bbb . 6) (ccc . 7)) ?what)

___ (assq ?who ((aaa . 5) (bbb . 6) (ccc . 7)) ?what)

* __ (assq bbb ?which (bbb . 6))

___ (assq ?who ((aaa . 5) (bbb . 6) (ccc . 7)) (bbb . 6))

If you had the rule [I] as the first rule, then the query result would be:

(assq bbb ((bbb . 6) . ?var) (bbb . 6)) displaying the undesired variable. If you had the rule [II] as the first thing, the query result would be:

(assq bbb (?irrelevant1 (bbb . 6)) (bbb . 6))

(assq bbb (?irrelevant2 ?irrelevant1 (bbb . 6)) (bbb . 6))

(assq bbb (?irrelevant3 ?irrelevant2 ?irrelevant1 (bbb . 6)) (bbb . 6))

Not knowing when to stop.

All the other queries are valid.

1

Computer Science 61A Study Group

Student Learning Center

Leader: Joo-Rak Son

Week 15, December 6 th and 8 th

4. Memoization

(a)

(define (cc amount kinds-of-coins)

(let ((table (make-table amount kinds-of-coins #f)))

(define (helper amount kinds-of-coins)

(cond ((= amount 0) 1)

((or (< amount 0) (= kinds-of-coins 0)) 0)

(else (let ((lookup (lookup-table table amount kinds-of-coins)))

(if lookup lookup

(let ((result

(helper (+ (cc (- amount (first-denomination

kinds-of-coins))

kinds-of-coins)

(cc amount (- kinds-of-coins 1)) ))))

(insert-table! table amount kinds-of-coins result)

result)))))))

(helper amount kinds-of-coins)))

(b)

(c)

Any tree-recursive function that has to look at every node of the tree, even if two equal nodes appear within it: countatoms, equal?, deep-reverse, and subsets are examples.

5. Where would we implement square-bracket?

Something else. You need to be able to parse first and then evaluate.

2

Download