Lisp for Java Users: Trivial Reader

We can now implement a very simple reader class for simplified Lisp lists. The class header and constructor look like this:

public class ListReader { private static final char OPEN_PAREN = '('; private static final char CLOSE_PAREN = ')'; private final PeekStream stream; public ListReader (final PeekStream stream) { = stream; } }

Here is the read method:

public Object read () throws IOException { stream.skipBlanks (); final int chr = stream.peekChar (); if (chr == OPEN_PAREN) { stream.readChar (OPEN_PAREN); final List<Object> result = new ArrayList<> (); while (!stream.peekChar (CLOSE_PAREN)) { result.add (read ()); stream.skipBlanks (); } stream.readChar (CLOSE_PAREN); return result; } final StringBuilder buffer = new StringBuilder (); while (!Character.isWhitespace (stream.peekChar ()) && stream.peekChar () != OPEN_PAREN && stream.peekChar () != CLOSE_PAREN) { buffer.append ((char)stream.readChar ()); } return Double.parseDouble (buffer.toString ()); }

The first part of this method reads everything in a balanced pair of parentheses as a List, using the read method recursively for the list content. The second part of this method reads characters that are not blanks or parentheses into a StringBuilder buffer and parses that as a double float number. You can download and run this code yourself, using a simple ReadDemo class with a main method.