CS170
Project Assignment #5
DUE : Monday, 12/7.
Make your interpreter even nicer than it is now. Add the following capabilites:
(1) Arithmetic functions: +, -, *. Note that addition and multiplication take any number of arguments (e.g., (+ 3 4 5) returns 12). This will require you to recognize when an atom is a number, to convert back and forth between strings and numbers, and probably will entail the most work in this assignment.
(2) Logical functions: AND, OR and NOT. Note again that AND and OR take any number of arguments. AND returns the last value computed in its arguments, if they are all non-#f, and #f otherwise; OR returns the first non-#f argument if there is one, and #f otherwise. It's a short-circuit evaluation in both cases. NOT is just a synonym for NULL?.
(3) Relational operators: <, >. Naturally, these apply only to numbers.
(4) Other miscellaneous functions which you may not have added yet:
- list : Takes any number of arguments and returns a list of them.
For example, (list 'a 'b 'c) returns (a b c).
- cadr, caddr, cadddr and caddddr : Returns the second, third, fourth....
element of a list, respectively.
- list? : A predicate that returns #t if the argument is a list, #f otherwise.
- number? : A predicate that returns #t if the argument is a number, #f otherwise.
- last : return the last item of a list.
- length : return the length of a list.
When you're all done, your interpreter should be capable of executing
(for example) the following solution to the Towers of Hanoi problem:
(define (tower-of-hanoi n) (transfer 'A 'B 'C n))
(define (move-disk from to)
(list (list 'move 'disk 'from from 'to to)))
(define (transfer from to spare n)
(cond ((equal? n 1) (move-disk from to))
(else (append (transfer from spare to (- n 1))
(append (move-disk from to)
(transfer spare to from (- n 1)))))))
((tower-of-hanoi n) returns a list of the correct moves to get n disks from pin A to pin B using pin C as a spare.) I can provide you with additional examples to serve as a test bed.
Other things you might consider doing (for extra credit, after all the above is done) include:
- Local binding via the LET special form.
- Pretty-printing lists (this would be very useful). Instead of
having a list come out like this,
((this is a really long list to illustrate) (the problems with having lists
spill over) (from one line to another))
print it out like this, indenting the right amount to expose the
structure:
((this is a really long list to illustrate)
(the problems with having lists spill over)
(from one line to another))
(Warning: To do this in general is probably somewhat trickier than
you may think.)
Here are some functions to try out on your
interpreter. There are several versions of some of them, reflecting some
of the varied ways of dealing with the empty list and quotes.
Back to CS170 Assignments.