[3-9] Closures don't seem to work properly when referring to the iteration variable in DOLIST, DOTIMES, DO and LOOP.

DOTIMES, DOLIST, DO and LOOP all use assignment instead of binding to
update the value of the iteration variables. So something like
   
   (let ((l nil))
     (dotimes (n 10)
       (push #'(lambda () n)
	     l)))

will produce 10 closures over the same value of the variable N. To
avoid this problem, you'll need to create a new binding after each
assignment: 

   (let ((l nil))
     (dotimes (n 10)
	(let ((n n))
	  (push #'(lambda () n)
		l))))

Then each closure will be over a new binding of n.

This is one reason why programmers who use closures prefer MAPC and
MAPCAR to DOLIST.
Go Back Up

Go To Previous

Go To Next