💾 Archived View for tilde.club › ~crmsnbleyd › state-without-classes.gmi captured on 2024-03-21 at 15:04:13. Gemini links have been rewritten to link to archived content

View Raw

More Information

-=-=-=-=-=-=-

Title: When you might want classes

Date: 2024-02-19

The web version of the crafting interpreters book is available to read for free. It uses Java, a popular Object-Oriented language to explain the implementation of an interpreter for a simple language. It does not actually do so in a language-agnostic way (which would obviously be pretty hard to do), thus using an Object-Oriented approach but the language I am using to go through it, Common Lisp, while having an impressive implementation of object-oriented programming, does not really prefer any programming style in particular.

web version of the crafting interpreters book

an impressive implementation of object-oriented programming

I would not like to pull in classes till they are absolutely needed (and they definitely might at some point when creating an interpreter), but the book adds features as it goes along, increasing the complexity of the implementation slowly.

For example, one of the first pieces of code uses the Java Scanner class to split a line of input into tokens. This usually occurs on-demand, with the user calling scanner.token() to get the next token. The code in question just splits it into an array of tokens, sidestepping any complexity mentioned here, but I accidentally made things harder for myself be overlooking that.

Anyway, the `scanner` class will have the string in question stored in some member variable, with a pointer to the current location in the generating process. All of this is hidden from the caller, so that it's just a simple call to get the next token.

We do not have this luxury in a non-OO environment, and have to handle everything ourselves. In this case, the state space is modeled entirely through function signatures, somewhat like:

:::haskell
nextToken :: String -> Char -> (String ,String)

Where the first `String` is the input, `Char` is the delimiter, and the output tuple represenst the output token, and the rest of the string.

What was being handled by a class is now passed to any calling functions, which are free to do whatever they wish with the output, even discard it completely.

This _might_ lead to unintended consequences, so the OO approach can be considered safer.

It's a bit tedious to implement, however.

Back to index