Homework 4
Lisp Evaluator (Part 2)
LISP (List Processing) is a family of programming
languages where the program is composed solely of linked lists.
Each list in any Lisp dialect is surrounded by parentheses, with
the elements delimited by spaces (and ordered from left to
right). The first element is assumed to be the function, and
the remaining elements are the parameters to this function.
A list of this form is also called an s-expression.
For example:
(+ 1 2 3)
Is a simple program in Lisp which would evaluate to 6
An atomic list is a list that contains no other lists.
Your goal is to implement addition, multiplication, and
subtraction over atomic lists according to the specified
interface.
This should be an extension of Lab 4,
however the main method will now be in the class you create for
this assignment, and not in Lisp.java.
Write a class called Parser which
will be responsible for parsing compound s-expressions into
atomic s-expressions.
Your class must do the following:
-
Define the following non-static methods:
-
getSexp
Finds the next atomic s-expression in the file.
-
params
-
repl: An instance of
a class implementing Repl. You should have already
completed this in Lab
4, so you may use the class you have written
for that assignment.
-
scan: A Scanner over
some s-expressions. We will be using a Scanner(File)
for this assignment.
-
parenCount: The
(integer) number of unmatched parentheses
encountered so far.
-
return An atomic s-expression as a String
-
A main method that asks the user
to enter a file to parse, then calls getSexp on a Scanner over
that file.
A good strategy is to parse the file character by character,
and build up the s-expression as a String. Done this way, you have
4 cases to consider:
-
The character is '('
In this case you have found a
nested s-expression, so you should make a recursive call to
getSexp. Make sure to update the parameters as appropriate.
-
The character is ')'
In this case you are closing
off the s-expression. Do any necessary updates to the string
and pass off the s-expr to
your eval method from Lab
4's Lisp class. Then return this
result.
-
The character is whitespace ('\n', '\t', or ' ')
You may want to make it easy on
your read and convert all
whitespace to a single space for ease of parsing later.
-
Otherwise
Add the current character to the
s-expression you are building
In addition, you might find the following methods useful:
-
«scanner».useDelimiter("")
Force the scanner to have no delimiter, so every call
to next returns only the next
character.
-
«string».replaceAll(" +", " ")
Replace multiple instances of a space with a single space in the given string.
-
«string».replaceAll(" \\)", "\\)")
Replace the sequence ' )' with a single closing bracket ')' in the given string.
-
«string».replaceAll("\\( ", "\\(")
Replace the sequence '( ' with a single closing bracket '(' in the given string.
Using this input file
Enter the name of a lisp file
test.lisp
6
8
16
Upload the .java file to the dropbox