Search the FAQ Archives

3 - A - B - C - D - E - F - G - H - I - J - K - L - M
N - O - P - Q - R - S - T - U - V - W - X - Y - Z - Internet FAQ Archives

FAQ: Lisp Frequently Asked Questions 3/7 [Monthly posting]
Section - [3-9] Closures don't seem to work properly when referring to the iteration variable in DOLIST, DOTIMES, DO and LOOP.

( Part1 - Part2 - Part3 - Part4 - Part5 - Part6 - Part7 - Single Page )
[ Usenet FAQs | Web FAQs | Documents | RFC Index | Business Photos and Profiles ]

Top Document: FAQ: Lisp Frequently Asked Questions 3/7 [Monthly posting]
Previous Document: [3-8] Name conflict errors are driving me crazy! (EXPORT, packages)
Next Document: [3-10] What is the difference between FUNCALL and APPLY?
See reader questions & answers on this topic! - Help others by sharing your knowledge

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)

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

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

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

This is one reason why programmers who use closures prefer MAPC and

User Contributions:

Comment about this article, ask questions, or add new information about this topic: