|
|
|
|
|
by chubot
3201 days ago
|
|
Honest question, why have local scopes at all? IIRC, Lox is a dynamic object-oriented language. Python has a flat scope per function, and closures aren't all that common in idiomatic Python code. Objects are much more common. JavaScript also had a flat scope per function until ES6. On the other hand, closures are very idiomatic in JavaScript, and objects are a little weak. Looking at the previous chapter [1], from someone familiar with OOP, the makeCounter and Point examples just seem to be awkward ways of writing classes, no? Particularly for an educational language, why have two ways of doing the same thing? [1] http://www.craftinginterpreters.com/functions.html |
|
Closures are common in "idiomatic" Lox code. Or, at least, I want Lox to be a language that doesn't have pitfalls around using closures and local variables.
Because Lox is syntactically C-ish, I also think it's important that its scoping rules roughly follow C and friends.
> JavaScript also had a flat scope per function until ES6.
Right, which is evidence that not having local scopes was a mistake. Adding "let" was a very big deal and wouldn't have been done unless the semantics of "var" really were not what users wanted.
I talk a little more about function scope in the context of implicit declaration here:
http://www.craftinginterpreters.com/statements-and-state.htm...
> Looking at the previous chapter [1], from someone familiar with OOP, the makeCounter and Point examples just seem to be awkward ways of writing classes, no? > > Particularly for an educational language, why have two ways of doing the same thing?
I think it's possible to go too far down the rabbit hole when deciding two things are the "same". Since you can implement integers using functions [1] why have both numbers and functions? You can implement control flow using closures and dynamic dispatch, so why have "if" [2]?
The pragmatic answers are:
1. Users probably don't think of functions and classes as "the same" even though only one is required for Turing completeness.
2. Most interpreters do not implement one in terms of the other, so having both lets us show the implementation techniques that are unique to each.
[1]: https://wiki.haskell.org/Peano_numbers [2]: https://www.gnu.org/software/smalltalk/manual/html_node/Cond...