lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


Mark Hamburg escribió:

> The reason closures (a la Scheme, for example) all reference the same
> copy of the variable in the outer scope is that it makes it easier to
> construct a number of things like objects where the variables in the
> outer scope are shared state. _Structure and Interpretation of
> Computer Programs_ probably covers this in a lot more depth.

Ah, but Scheme doesn't reference the same copy. From R5RS:

> `Do' expressions are evaluated as follows: The <init> expressions
> are evaluated (in some unspecified order), the <variable>s are bound
> to fresh locations, the results of the <init> expressions are stored
     ^^^^^^^^^^^^^^^
> in the bindings of the <variable>s, and then the iteration phase
> begins.

> Each iteration begins by evaluating <test>; if the result is false
> (see section see section Booleans), then the <command> expressions
> are evaluated in order for effect, the <step> expressions are
> evaluated in some unspecified order, the <variable>s are bound
> to fresh locations, the results of the <step>s are stored in the
     ^^^^^^^^^^^^^^^
> bindings of the <variable>s, and the next iteration begins.

(Note: Scheme "do" statements are "do until" rather than "do while"
as in C; this always gets me when I'm switching back and forth. So
the word "false" above is not a typo.)

Yes, SICP does cover this issue.

It is certain that both your suggestion and Roberto's correctly
bind the closures. However, my point is that having the language
implement this rather than forcing ugly workarounds is simpler and
faster, and there is no reason I can see for the existing
behaviour.

The extra efficiency of having a single copy rather than multiple
copies is mostly illusory. If the local is never turned into a
closure, the cost is one stack slot. If the local is turned into
a closure, you would have had to do that anyway, presumably by
one of the suggested workarounds. As I showed yesterday, the
implementation code in the VM for the "fresh binding" approach
is actually shorter and faster in the case of table iterations
and only one store longer in the case of numeric iterations.

And that is why Scheme (and other languages) do it the way
they do: it is what the programmer wants, and it doesn't cost
anything to do it.

R.