[Openmcl-devel] Closures
Pascal J. Bourguignon
pjb at informatimago.com
Sun Apr 20 09:09:08 PDT 2014
Taoufik Dachraoui <dachraoui.taoufik at gmail.com> writes:
> Hi
>
> Can someone explain the following:
>
> ? (let ((fn nil)) (dotimes (k 2) (push (lambda () (print k)) fn))
> (dolist (f fn) (funcall f)))
> 2
> 2
> NIL
This is not conforming. You could get any output.
The conforming code is:
(let ((fn nil))
(dotimes (k 2)
(let ((k k))
(push (lambda () (print k)) fn)))
(dolist (f fn)
(funcall f)))
and it outputs:
1
0
> ? (let ((fn nil)) (dotimes (k 2) (let ((r k)) (push (lambda () (print
> r)) fn))) (dolist (f fn) (funcall f)))
>
> 1
> 0
> NIL
> ? (defvar r 10)
> R
> ? (let ((fn nil)) (dotimes (k 2) (let ((r k)) (push (lambda () (print
> r)) fn))) (dolist (f fn) (funcall f)))
>
> 10 ?????
> 10 ?????
> NIL
> ?
r is special.
You should have respected the convention for special variables:
(defvar *r* 10)
(progn
(let ((fn nil))
(dotimes (k 2)
(let ((*r* k))
(push (lambda () (print *r*)) fn)))
(dolist (f fn)
(funcall f)))
(let ((fn nil))
(dotimes (k 2)
(let ((r k))
(push (lambda () (print r)) fn)))
(dolist (f fn)
(funcall f))))
outputs clearly:
10
10
1
0
--
__Pascal Bourguignon__
http://www.informatimago.com/
"Le mercure monte ? C'est le moment d'acheter !"
More information about the Openmcl-devel
mailing list