I’ve been working through a tutorial on common lisp, and I’ve just been introduced to incf and dolist , I wanted to see if I properly understood how dolist functions by making a function inc-list that would increment every element of a list by one:
(defvar a-list (list 1 2 3))
(inc-list a-list) => (2 3 4)
Here is how I defined inc-list
(defun inc-list (list)
(progn
(dolist (element list)
(incf element))
list))
This doesn’t seem to work. when I try (inc-list a-list) I get back (1 2 3) and
a-list => (1 2 3). This wouldn’t bother me as much if it weren’t for the fact that doing :
(incf (car a-list))
(incf (cadr a-list))
(incf (caddr a-list))
gives me a-list => (2 3 4). Is there some secret to what element means?
elementis bound to each of the elements of the list, in turn, i.e. the value of thecarof each pair is in a sense “copied” to it. Then,incfis called onelement, incrementing that variable’s value, but not the list position that it was taken from. It’s as if you’re doingHere too,
elementis incremented and then immediately “forgotten” each time because it’ssetq‘d to a new value. By contrast,(incf (car a-list))increments thecarofa-listin-place. If you want that behavior in a loop, then forget aboutdolistandloop onthe list instead: