Dana Vrajitoru
C311 Programming Languages
C311 Homework 3
Due Date: Wednesday, February 1, 2023.
Note. The results of the entire exercise should be uploaded
to Canvas, Assignments, Homework 3, as the file hw3.el.
In this homework we will focus on the loops dolist
and dotimes. You must use either of these two loops in at
least one of the functions below. Do not use dotimes in
combination with the length of a list, nor the while loop.
Reference for dotimes
and dolist.
(http://www.cs.iusb.edu/~danav/teach/c311/c311_elisp3.html)
Ex. 1
Write the following Lisp functions using either recursion or the
loops dotimes and dolist:
- a. A function called is-const that takes one
parameter that we can assume to be a list, and returns t if
all the elements of the list are identical to each other (or what we
could call, a constant list) and nil otherwise. Note that
both an empty list and one that has only one element can be considered
constant. Use the function equal to test for
equality. Implementation suggestion: with the dolist loop.
Examples of results:
(is-const '()) ; t
(is-const '(a)) ; t
(is-const '(1 2 3)) ; nil
(is-const '(5 5 5 5)) ; t
- b. A function called element-i taking two
parameters. You can assume that the first one is a list and the second
one a non-negative number. 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. Implementation suggestion: you can use either the
loop dolist with a counter, or the loop
dotimes in combination with the
function pop. Recursion also works.
Examples of results:
(element-i '(1 2) 4) ; nil
(element-i '(a b c d e) 4) ; 'e
(element-i '(3 1 2 6) 0) ; 3
- c. A function called is-sorted that takes one
parameter that is a list and returns true (t) or false
(nil) based on whether the list is sorted in ascending order
or not. Note that an empty list or a list with a single element are
sorted by default. Implementation suggestion: using dolist
where you store the previous element in a variable as you go along, or
recursion.
Examples of results:
(is-sorted '()) ; t
(is-sorted '(10)) ; t
(is-sorted '(5 5 5)) ; t
(is-sorted '(4 3 2 1)) ; nil
(is-sorted '(2 5 9 12 14)) ; t
- d. A function called reverse that reverses a
list. The function takes one parameter that you can assume to be a
list, and returns another list which is the reverse of the argument
(you don't need to do the operation in place). You can use the
function list that creates a list out of its arguments,
or append that concatenates two lists and returns the
result. Implementation suggestion: using dolist or recursion.
Examples of results:
(reverse '()) ; '() or nil
(reverse '(2)) ; (2)
(reverse '(1 2 3)) ; (3 2 1)
- Show a few examples of testing these functions.
Upload to Canvas, Assignments, Homework 3, the Lisp
file hw3.el.