On Wed, Jan 29, 2003 at 08:51:54AM +0100, Fabrizio Morbini wrote:
> Hi, thank you very much for all the response to my previous mail!
>
> Take this example:
>
> (setq a 6)
Please stop using SETQ like this. Use LET instead, like you did in the
very last example below.
> (flet (
> (prova () (print a))
> )
> (let ((a 4))
> (print a)
> (prova)))
>
> (print a)
I would appreciate if you would format your code properly. Use Emacs or
similar.
(flet ((prova () (print a)))
(let ((a 4))
(print a)
(prova)))
> The output is:
>
> print: 4
> prova: 6
> print: 6
>
> This is because the function prova isn't in the lexical environment
> created by let...
>
> using defvar instead of setq the output is:
>
> print: 4
> prova: 4
> print: 6
>
> *Why the let hidden the dinamic scope variable "a" (defvar) but not when
> this is created by setq? My response is: because let start a new empty
> lexical environment that doesn't contain "a" so let can't hidden a
> variable that can't see... is correct?
No. When LET is used on a special variable, such as that created with
DEFVAR, it does not create a lexical binding but rather it creates a
special binding. This new binding is in effect for all subsequent code
(indefinite scope) until the LET form is exited (dynamic extent).
This is one of the reasons for the *VAR* convention of special
variables; so that you don't create a special binding with LET when you
really mean to create a lexical binding.
Consider:
(defvar *a* 1)
(defun g ()
*a*)
(defun f ()
(let ((*a* 2)) ; special binding established
(g))) ; call G with new special binding in effect
Compare the results of (f) and (g).
--
; Matthew Danish <andrew.cmu.edu at mdanish>
; OpenPGP public key: C24B6010 on keyring.debian.org
; Signed or encrypted mail welcome.
; "There is no dark side of the moon really; matter of fact, it's all dark."