munificent / craftinginterpreters

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

New Java features may help out #1164

Closed RupertBenWiser closed 6 months ago

RupertBenWiser commented 6 months ago

I'm currently chipping away at this awesome book during my pat leave (very slowly as you can imagine!).

A couple of new Java features have meant that I haven't had to use the tools directory which removes the codegen which seems like a little bit of a distraction. Namely records, and switch expressions. The records have meant that the code has been small enough to not really be a lot of churn, and the switch expressions allow us to efficiently pattern match so I haven't had to use the visitor pattern (from my brief Google, the JVM does seem to have optimisations for this).

I'm still at the statements chapter so I don't know if this ends up being a pain later on.

Here is an example of how the records look: https://gitlab.com/BenWiser/crafting-interpreters/-/blob/48c9c1a9be96136804300818cef0a0d932b1c77b/app/src/main/java/org/lox/Expr.java

Here is an example of how the switch expressions look: https://gitlab.com/BenWiser/crafting-interpreters/-/blob/48c9c1a9be96136804300818cef0a0d932b1c77b/app/src/main/java/org/lox/Interpreter.java#L45

Let me know if you also aren't keen on using newer Java features.

munificent commented 6 months ago

Yeah, there's a lot in the book that would be nicer with newer Java features. At the same time, I'm mostly trying to use Java as a pseudocode that can be read by anyone familiar with Java/C++/C#/TypeScript/etc., so I try to confine the book to using a subset of Java features that are shared by most object-oriented statically typed languages.

So, at least until I do a second edition of the book (which I currently have plans to ever do!), it will stay on the set of Java features it already uses.

(As an aside: We recently added pattern matching, switch expressions, and destructuring to Dart. I've migrated some hobby languages written in Dart to use them and they really are wonderful for that kind of code.)