munificent / craftinginterpreters

Repository for the book "Crafting Interpreters"
http://www.craftinginterpreters.com/
Other
8.84k stars 1.04k forks source link

introduce a lambda expression or make function declaration an expression #99

Closed forax closed 7 years ago

forax commented 7 years ago

Writing lox code is currently a pain in the ass because one can not write foo(fun() { ... }) or foo(fun bar() { ... })
but has to write fun bar() { ... } foo(bar); which is less readable and leaks bar to the rest of the script.

I also think that it's interesting to show that a lambda is just a closure with no name.

forax commented 7 years ago

Here is an example of code that you have to read backward, because there is no lambda. https://github.com/forax/craftinginterpreters/blob/master/lox/interpreter.lox#L224

munificent commented 7 years ago

Ah, yes! I debated this off and on quite a bit. In a real language, absolutely, yes, there would be a lambda form. As you note, the only differences are that it doesn't have a name and that it's allowed in expression position.

The latter makes parsing a little annoying. Because of expression statements, it's possible to see fun at the beginning of a statement and not know if it's a function declaration or a lambda in an expression statement until after you see the name token. That's not intractable, but it's a little ugly, and I try to avoid kludgy code when possible.

My other hesitation was because once you have function declarations and closures, lambdas don't really teach you anything particularly interesting. I felt it would be extra tedious code to walk through without too much value.

So my tentative plan was to leave lambdas out of the language but probably add a challenge for users to implement them themselves. If you're extending Lox yourself to try to make it useful, they are certainly a natural feature. (Along with lists!)

I'll leave this open to revisit it when I'm working on the functions chapter and have a better sense of if it would make sense to work them in, but my current plan is to omit them from the book. Thank you for bringing this up!

munificent commented 7 years ago

OK, I added a challenge exercise for these and implemented them in the answer key. I don't think it was too difficult to add them on the side, and I think it made an already long chapter a little shorter to leave them out of the main language.