[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: "defmacro" and "local variables" and "let" and "nconc" strange behav
From: |
jack-mac |
Subject: |
Re: "defmacro" and "local variables" and "let" and "nconc" strange behaviour... |
Date: |
Mon, 14 Jan 2013 01:04:47 -0800 (PST) |
User-agent: |
G2/1.0 |
Le dimanche 13 janvier 2013 15:18:46 UTC+1, Oleksandr Gavenko a écrit :
> On 2013-01-13, Oleksandr Gavenko wrote:
>
>
>
> > I wrote simple macro:
>
> >
>
> > (defmacro my-filter (pred list)
>
> > "Construct list with elements from LIST which satisfy PRED."
>
> > (let ( (r (make-symbol "r_")) )
>
> > `(let ( (,r '(nil)) )
>
> > (mapc (lambda (item)
>
> > (when (,pred item)
>
> > (nconc ,r (cons item nil))))
>
> > ,list)
>
> > (cdr ,r))))
>
> >
>
> > When I evaluate several times:
>
> >
>
> > (my-filter (lambda (x) x) '(1 nil "a"))
>
> >
>
> > I get sequentially:
>
> >
>
> > (1 "a")
>
> > (1 "a" 1 "a")
>
> > (1 "a" 1 "a" 1 "a")
>
> > (1 "a" 1 "a" 1 "a" 1 "a")
>
> >
>
> > When I eval:
>
> >
>
> > (pp (macroexpand '(my-filter (lambda (x) x) '(1 nil "a"))))
>
> >
>
> > I get:
>
> >
>
> > (let
>
> > ((r_
>
> > '(nil 1 "a" 1 "a" 1 "a" 1 "a" 1 "a" 1 "a" 1 "a" 1 "a")))
>
> > (mapc
>
> > (lambda
>
> > (item)
>
> > (when
>
> > ((lambda
>
> > (x)
>
> > x)
>
> > item)
>
> > (nconc r_
>
> > (cons item nil))))
>
> > '(1 nil "a"))
>
> > (cdr r_))
>
> >
>
> > Why instead of '(nil) I get something else?
>
>
>
> I found fix by changing '(nil) to (list nil). Please explain why first variant
>
> fail?
>
>
>
> --
>
> Best regards!
To understand it, just try:
(defun foo (x)
(let ((l '(0)))
(nconc l (list x))))
(foo 1)
(foo 2)
This looks like a closure!