All of these problems should be done without using side effects (i.e. redefining variables or using set!). Be sure to test your functions on various cases, including empty lists, simple lists with no sublists, complex lists, etc.
(define x '(3 5))
(define y (cons 1 x))
(define z (list 'a 'b x))
(define w (cons x y))
(define a '(dog cow pig))
(define b (reverse a))
(define c (cons a b))
(define d (append a b))show the value that results from evaluating each of the following expressions. If something is wrong, say so. (Obviously you could trivialize the problem by typing these expressions into a Scheme interpreter and transcribing the results. Feel free to use a computer to check your answers, but be sure you can answer the questions without using a machine.)
(car b)
(cadr b)
c
(cadar c)
(cons (cdr a) b)
(equal? a b)
(equal? d (reverse d))
(equal? (car c) a)
(eq? (car c) a)
(eq? d (reverse d))
(cons '(car a) b)
(pair? a)
Write and test Scheme functions to solve the following problems. You
should save all of your function definitions in a single source file. In
DrScheme you can use File->Save definitions as
to create a file that contains your function definitions.
The normal convention is to use the extension .scm
to end Scheme
file names.
You should turn in both the function definitions
themselves and a printout showing a Scheme session where you test the
functions. Your test cases should be sufficient to show that the functions
work correctly (i.e., works on both empty and non-empty lists, etc.). In
DrScheme, you can use File->Print Interactions
to print the
session transcript.
gcd(x,y)
that yields the greatest common divisor of positive integers x
and y
.(2nd-last '(x y (b c) (d (e f))) => (b c)
(2nd-last '(ha)) => ()
sum-digits
that returns the sum of all the digits
of the integers in a list. Embedded lists and things that are not integers
should be ignored. For example:(sum-digits '(23 3 44 9)) => 25
(sum-digits '(3 fooled-you 41 (30))) => 8
Hint: feel free to define an additional, auxiliary function if it makes your life simpler.
depth
that returns the depth of a list. The
depth of an empty list is 0, a list containing no sublists is 1, etc. Examples::(depth '()) => 0
(depth '(a b c)) => 1
(depth '((((a))))) => 4
(depth '(a (b (c) d) (e ((f) g))) => 4
(define (fib n) (cond ((= n 0) 0) (= n 1) 1) (else (+ (fib (- n 1)) (fib (- n 2))))Write a new function
fibt
that calculates the nth Fibonocci
number in linear time. Remember, you may not use assignments (set!
)
or global variables (other than global function names, of course).
Hint: Tail recursion. You may also find an it useful to define an auxiliary function.
For this (as well as most) assignments, you should turn in your work both electronically over the web and on paper.
Turn in a copy of your Scheme source file from part II using this turnin form.
Hand in the following: