[ By Archive-name | By Author | By Category | By Newsgroup ]
[ Home | Latest Updates | Archive Stats | Search | Usenet References | Help ]

    Search the FAQ Archives

Part1 - Part2 - Part3 - Part4 - Part5 - Part6 - Part7 - Single Page

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?


[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.



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?

Part1 - Part2 - Part3 - Part4 - Part5 - Part6 - Part7 - Single Page


[ By Archive-name | By Author | By Category | By Newsgroup ]
[ Home | Latest Updates | Archive Stats | Search | Usenet References | Help ]


Send corrections/additions to the FAQ Maintainer:
ai+lisp-faq@cs.cmu.edu

Last Update July 09 2008 @ 00:13 AM

© 2008 FAQS.ORG. All rights reserved.