due 10/11/99
The topics covered in this assignment include: tail-recursion, applicative programming (first class functions), lexical scoping, and tree traversal. Do not use any functions with side-effects.
Try these questions out before section.
(define x 5) (define y 4)What would the values of the following scheme expressions?
(let ((x 3) (z (+ x 1)) ) (* x y z) )
(let* ((x 3) (z (+ x 1)) ) (* x y z) )
(let* ((z (+ x 1)) (x 3) ) (* x y z) )
(list (let ((x 3) (z (+ x 1)) ) (* x y z) ) x y )
(define x 5) (define y 4) (define (foo x) (+ x y) ) (define (bar y) (foo y) )What is the value of
(bar 10)
(flatten `(1 ((2) 3) (4))) => (1 2 3 4)
These are some sample problems that we will be discussing in section.
;; assuming f has no side-effects and that ;; x and y are defined and are valid arguments to f (define g (curry f x)) (equal? (g y) (f x y)) => #t ;; more examples (define add5 (curry + 5)) (define add2 (curry + 2)) (add5 10) => 15 (add5 2) => 7 (add2 10) => 12
(filter number? '(a b 1 3 c 4 d) => (1 3 4) (filter symbol? '(a b 1 3 c 4 d) => (a b c d) (filter symbol? '()) => ()
Complete the following. You do not have to handle errors in input gracefully. Do not forget to turn in output with your source code.
A polynomial ax3 + bx2+cx +d can easily be evaluated using Horner's Rule as (x(x(x(a)+b)+c)+d). This gives a very natural recursive way to evaluate a polynomial at some point x. Take the first coefficient, multiply by x, and add the next coefficient. Then take this value, multiply by x, and add the next coefficient, etc. Define a tail-recursive function eval-poly that takes a point x and a list of coefficients coefs and evaluates the polynomial at the point x. Assume the coefficients are ordered such that, x2+2x+3 is expressed by the list (1 2 3). For example:
(eval-poly 1 '(1 2 3)) => 6 ;; 1 + 2 + 3 (eval-poly 2 '(1 2 3)) => 11 ;; 1*2^2 + 2*2 + 3
Recall the sum-tree function written in class. It can be reorganized to look much like the solution to the flatten function in Part I.
(define (sum-tree tree) (cond ((null? tree) 0) ((pair? tree) (+ (sum-tree (car tree)) (sum-tree (cdr tree)))) (else tree) ) )
Some example usages:
(contains (emptytable) 'x) => #f (define t1 (insert (emptytable) 'x 5)) (contains t1 'x) => #t (lookup t1 'x) => 5 (lookup t1 'y) => symbol-not-found (define t2 (insert (insert t1 'y 10) 'z 9)) (define t3 (insert t2 'foo '(1 2 3))) (map (curry lookup t3) '(x y z)) => (5 10 9) (lookup t3 'foo) => (1 2 3)
Your table should be able to hold any type of data not just numbers.
Hint: To compare two symbols you can convert them to strings using symbol->string and then compare them as strings using the string<?, string>?, etc. relations.