Time: Wed 10/25/17 2 pm
Consider the following implementation:
def tree(label, branches=): return [label] + branches def label(tree): return tree def branches(tree): return tree[1:]
There are multiple ways to get started on playing with such tree structure! As a few examples:
try: pass # Some bunch of stuff except Exception as e: pass # Do something regarding the exception
1 ; 1 True ; True
(define a 1) ; a a ; 1 (define (foo x) (+ x 2) ) ; foo ; Is equivalent to the following (define foo (lambda (x) (+ x 2) ) ) ; foo (foo 2) ; 4
(+ 1 2) (display 2) (print 1) (cons 1 2) (list 1 2)
= predicate when you wish to test whether two numbers are equivalent.
eqv? predicate when you wish to test whether two non-numeric values are equivalent.
(if True 1 2) ; 1 (if True (/ 1 1) (/ 1 0) ) ; 1 (cond (False (/ 1 0)) (True 1) (else 100) ) ; 1 (lambda (x) (/ 1 0) ) ; (lambda (x) (/ 1 0)) (and 0 False 1) ; False (or 5 False (/ 1 0)) ; 5
(and ...) returns the first false value, otherwise the last one.
(or ...) returns the first true value, otherwise the last one.
False is the only false value.
'a ; a (quote a) ; a '(1 2) ; (1 2) (quote (1 2)) ; (1 2) '(1 . 2) ; (1 . 2) '(1 . ()) ; (1) '(1 . (2 . (3))) ; (1 2 3)
Implement the Scheme procedure directions, which takes a number
n and a symbol
sym that is bound to a nested list of numbers. It returns a Scheme expression that evaluates to
n by repeatedly applying
cdr to the nested list. Assume that
n appears exactly once in the nested list bound to
Hint: The implementation searches for the number
n in the nested list
s that is bound to
sym. The returned expression is built during the search. See the tests at the bottom of the page for usage examples.
(define (directions n sym) (define (search s exp) ; Search an expression s for n and return an expression based on exp (cond ((number? s) ) ((null? s) nil) (else (search-list s exp)) ) ) (define (search-list s exp) ; Search a nested list s for n and return an expression based on exp (let ( (first ) (rest ) ) (if (null? first) rest first) ) ) (search (eval sym) sym) ) (define a '(1 (2 3) ((4)))) (directions 1 'a) ; expect (car a) (directions 2 'a) ; expect (car (car (cdr a))) (define b '((3 4) 5)) (directions 4 'b) ; expect (car (cdr (car b)))
What expression will
(directions 4 'a) evaluate to?