Dana Vrajitoru
C311 Programming Languages
Homework 3
Due Date: Thursday, September 18, 2008.
Note. The results of the entire exercise should be sent in
one file with the extension .el as an attachment to an email.
Ex. 1 Write the following Lisp functions using the loops
dotimes and dolist:
- a. A function that returns the last element in the
list. For this one, use the loop dolist and not the
builtin that gives you the length of the list.
- b. A function called element-i taking two
parameters, the first which you can assume to be a list, and the
second a number that you can assume non-negative. The function must
return the i-th element of the list. We'll assume that the car of the
list is the element number 0, the next one is number 1, and so on. If
the index is higher than the length of the list, the function should
return nil. You can use either the loop dolist with a counter, or the
function dotimes in combination with the function pop.
- c. A function that generates the first n numbers in
the Fibonacci sequence and returns them in a list. The number n
will be the provided as a parameter for this function. The first two
Fibonacci numbers are 1 and 1, and any new one is obtained as the sum
of the previous two (the next one is 2, followed by 3, 5, 8,
etc.). The numbers can be stored in the list in reverse order. Use a
dotimes loop in this function and the function push to add
numbers to the list.
- d. A function that reverses a list using the dolist
loop. The function takes ona parameter that you can assume is a list,
and returns another list which is the reverse of the first
one.
- e. A function called similar that takes two
parameters which are lists and returns true (t) if the lists have the
same length and if each of their elements is equal to the element of
the other list in the same position. Use the predicate equal
for the comparison. Don't use the function element-i written above
because it will make your function quadratic. Note that if both lists
are empty, then they are equal.
- Show a few examples of testing these functions.
Send the file by email as an attachment. Note: anything but the Lisp
code and the result of the evaluation should be commented out in
the file.