Sarah44 wrote:However, the only thing is that the textbook says that we can solve the problem using only do. Is it really different from dolist? If yes, could you explain in what it is different?
DO is like C(++ or 99 specifically, I think)'s for loop, except you can have multiple variables being stepped at once, and it returns a value (either nil or a value you specify), like every Lisp form. The basic idea is that you specify some variables, each optionally having an initial value and a form that produces the next value, then you specify a termination condition, then you write the loop body.
EDIT: It's also sort of a recursion emulation. Note the similarity between the arguments to the recursive LIST-LENGTH call and the next value forms in the DO loop.
- Code: Select all
(defun list-length (list &optional (so-far 0))
(if list
(list-length (cdr list) (1+ so-far))
so-far))
(defun list-length-2 (list)
(do ((list list (cdr list))
(so-far 0 (1+ so-far)))
((null list) so-far)))