Lisp for Java Users: Trivial Interpreter

Previously, we implemented a Java application to read Lisp expressions. In this chapter we implement a simple Java application to process Lisp expressions as programs.

Take a look at the Symbol class. In addition to the Symbol name, it includes a value that can be changed. Now we can start implementing an interpreter for Lisp expressions. The first version won't do much, but can get the value of a Symbol if that is given as an expression. Notice that the value can be stored in a binding map inside the interpreter or in the Symbol itself. This will allow us to define global and local variable bindings. Simple accessor style methods allow another class to obtain the binding and set a variable binding in this context.

This class will be the start of our interpreter. This page has about 50 lines of code, which is more than any other page in this chapter.

public class Interpreter { private final Map<Symbol, Object> bindings; public Interpreter () { bindings = new LinkedHashMap<Symbol, Object> (); } public Interpreter (final Map<Symbol, Object> bindings) { this.bindings = bindings; } public Map<Symbol, Object> getBindings () { return bindings; } public void setValue (final Symbol symbol, final Object value) { if (bindings.containsKey (symbol)) { bindings.put (symbol, value); } else { symbol.setValue (value); } } public Object eval (final Object expression) { if (expression instanceof Symbol) { return evalSymbol ((Symbol)expression); } return expression; } private Object evalSymbol (final Symbol symbol) { if (bindings.containsKey (symbol)) { return bindings.get (symbol); } else { return symbol.getValue (); } } }
‚Äč