[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: Unreferenced symbols in closures, and a problem with closures in min
From: |
Stefan Monnier |
Subject: |
Re: Unreferenced symbols in closures, and a problem with closures in minor modes |
Date: |
Tue, 28 May 2013 21:28:44 -0400 |
User-agent: |
Gnus/5.13 (Gnus v5.13) Emacs/24.3.50 (gnu/linux) |
> (setq lexical-binding t)
> As expected, (let ((x 0)) (lambda () x)) -> (closure ((x . 0) t) nil x)
> But, (let ((x 0)) (lambda () 0)) -> (closure ((x . 0) t) nil 0)
> And, (lambda (x) x) -> (closure (t) (x) x)
> Why do closures' lexical environments include unreferenced symbols?
Because you're testing interpreted code: the interpreter does not take
the time to traverse the whole lambda body to figure out which variables
are free and which aren't. That could have a significant
performance impact. Rest assured that when you byte-compile this code,
only the free variables will be captured, tho.
> And why produce a closure with an empty environment, instead of just
> a lambda form?
Because the two are not equivalent in general: when running the body of
(closure (t) (x) <body>), `x' is lexically bound, whereas when running
the body of (lambda (x) <body>), `x' is dynamically bound.
> And I have a problem with unwanted closures in minor modes:
[...]
> Argh! Surely this is a misfeature?
Yup.
> I have no idea what the symbol i means or where it came from. If it
> were setting i to nil in the lexical environment, it would be (i),
> not i.
Indeed. A sole `var' in this environment is used to keep track of the
fact that a (defvar var) was encountered and hence `var' should be
treated as dynamically scoped when we run a `let'. Again, this only
applies to interpreted code.
> Also, the two closures are identical, yet add-hook isn't supposed to
> add duplicates.
No idea why that is, indeed.
To add&remove functions from hooks, it's much better to make sure you
actually pass the exact same object (not just one that should hopefully
be `equal').
Equality of functions is tricky business (both in theory and in practice).
Stefan