What does the term "element" mean in (dolist (list of elements) ...)?

I was working on a tutorial on general lisp, and I just got acquainted with incf and dolist , I wanted to know if I understood correctly how dolist functions perform the inc-list function, which will increase each list item by one:

(defvar a-list (list 1 2 3))

(inc-list a-list) => (2 3 4)

This is how I defined inc-list

 (defun inc-list (list) (progn (dolist (element list) (incf element)) list)) 

This does not work. when I try (inc-list a-list) , I return (1 2 3) and a-list => (1 2 3) . This would not bother me if it were not for the fact that:

 (incf (car a-list)) (incf (cadr a-list)) (incf (caddr a-list)) 

gives me a-list => (2 3 4) . Is there any secret to what element means?

+4
source share
2 answers

element attached to each of the elements of the list, in turn, that is, the car value of each pair is, in a sense, "copied" to it. Then incf is called on element , increasing the value of the variable, but not the position of the list from which it was taken. As if you do

 (defvar element (car a-list)) (incf element) (setq element (cadr a-list)) (incf element) (setq element (caddr a-list)) (incf element) 

Here also element incremented and then immediately β€œforgotten” every time, because it is setq for the new value. In contrast, (incf (car a-list)) increments the car of a-list in place. If you need this behavior in a loop, then forget about dolist and loop on list:

 (loop for position on lst do (incf (car position))) 
+4
source
 (defvar a-list (list 1 2 3)) 

Side note . Do not write global variables like this. Write *a-list* . Otherwise, the global dynamic variable affects your local variables.

 (defun inc-list (list) (progn (dolist (element list) (incf element)) list)) 

You do not need a PROGN . DEFUN already allows a sequence of forms, just like DOLIST .

 (defun inc-list (list) (dolist (element list) (incf element)) list) 

Enough.

DOLIST is a form in which a new (!) Local variable called ELEMENT is introduced.

DOLIST sets the ELEMENT value at each iteration. All you do is increase the ELEMENT value at each step of the iteration. Your side effect is lost. The original LIST is not changed. ELEMENT not used otherwise.

+2
source

Source: https://habr.com/ru/post/1380899/


All Articles