Subject: [clisp-list] Family of functions

From: Francisco Jesús Martín Mateos <[email-masked]>
Date: Fri, 26 Jan 2001 12:33:29 +0100

I want to build a family of functions, my first attempt was

(setq function-set-1
   (loop for i from 0 to 9 collect
     (lambda (x) (list x i))))

But this don't work properly:

(setf f1-6 (nth 5 function-set-1))

> (funcall f1-6 3)
; => (3 10)  !!! It will must be (3 5)

When I do the same with mapcar:

(setq function-set-2
      (mapcar (lambda (i) (lambda (x) (list x i)))
       '(0 1 2 3 4 5 6 7 8 9)))

(setf f2-6 (nth 5 function-set-2))

> (funcall f2-6 3)
; => (3 5)

What's the problem with loop?

---

From: Pierpaolo BERNARDI <[email-masked]>
Date: Fri, 26 Jan 2001 15:54:08 +0100 (MET)

>      (lambda (x) (list x i))))

Try:

(setq function-set-1
   (loop for i from 0 to 9 collect
     (let ((j i))
       (lambda (x) (list x j))))

> What's the problem with loop?

In the loop version you were using ten times the same variable, not ten
different variables.

P.

---

From: Sam Steingold <[email-masked]>
Date: 26 Jan 2001 11:56:55 -0500

> * In message <[email-masked]>
> * On the subject of "[clisp-list] Family of functions"
> * Sent on Fri, 26 Jan 2001 12:33:29 +0100
> * Honorable Francisco Jesús Martín Mateos <[email-masked]> writes:
>

(setq function-set-1
      (loop for i from 0 to 9 collect
            (let ((i i)) (lambda (x) (list x i)))))

should do what you want.

this is because in your version "i" is bound in turn to 0..9 and lambda
gets the binding, so all lambdas have the same "i", so to speak, which
changes values.

in my version, each lambda gets its own "i", bound specifically for it.

this is not a bug, but a subtle intricacy of Common Lisp.

-- 
Sam Steingold (http://www.podval.org/~sds)
Support Israel's right to defend herself! <http://www.i-charity.com/go/israel>
Read what the Arab leaders say to their people on <http://www.memri.org/>
The paperless office will become a reality soon after the paperless toilet.