Programming Assignment 6 (LISP Expressions)

Consider the following definition for "LISP expressions".

A LISP expression is defined as follows:

  1. A number is a LISP expression. (We can assume positive integers)
  2. if E1 and E2 are LISP expressions then so are (+ E1 E2), (- E1 E2), (* E1 E2), and (/ E1 E2).
  3. if L is a List Expression (defined below) then (car L) is a LISP expression.
A List Expression is defined as follows:
  1. if E1, E2, ..., En are LISP expressions where n>0 then (E1 E2 ... En) is a List Expression.
  2. if L is a List Expression then (cdr L) is a ListExpression.
Here are examples of valid LISP expressions:
34
(+ 20 30)
(* (+ 1 2) (/ 8 4))
(* (car (2 4 (+ 2 4) 8)) (/ 27 9))
(+ (car (2 3 4)) (car (cdr (cdr (9 8 7 6)))))
Using the following Lexer and Parser specifications (you will need to install the ply package in Python), complete the "Evaluator" program for Lisp and List expressions.

LispLexer.py

LispParser.py

Lisp.py (contains function templates for you to complete)

Here is a sample run:

mirage:p6-lisp raj$ python3 Lisp.py 
LISP: 34;
['NUM', ['num', 34.0]]

The value is 34.0

LISP: (+ 20 30);
['NUM', ['+', ['num', 20.0], ['num', 30.0]]]

The value is 50.0

LISP: (/ 9 (- 2 2));
['NUM', ['/', ['num', 9.0], ['-', ['num', 2.0], ['num', 2.0]]]]

EVALUATION ERROR: Divide by 0!

LISP: (* (+ 1 2) (/ 8 4));
['NUM', ['*', ['+', ['num', 1.0], ['num', 2.0]], ['/', ['num', 8.0], ['num', 4.0]]]]

The value is 6.0

LISP: (* (car (2 4 (+ 2 4) 8)) (/ 27 9));
['NUM', ['*', ['car', [['num', 2.0], [['num', 4.0], [['+', ['num', 2.0], ['num', 4.0]], [['num', 8.0], []]]]]], ['/', ['num', 27.0], ['num', 9.0]]]]

The value is 6.0

LISP: (+ (car (2 3 4)) (car (cdr (cdr (9 8 7 6)))));
['NUM', ['+', ['car', [['num', 2.0], [['num', 3.0], [['num', 4.0], []]]]], ['car', ['cdr', ['cdr', [['num', 9.0], [['num', 8.0], [['num', 7.0], [['num', 6.0], []]]]]]]]]]

The value is 9.0

LISP: (car (cdr (10)));
['NUM', ['car', ['cdr', [['num', 10.0], []]]]]

Cannot evaluate CAR of EMPTY List!

LISP: (+ 2 3 4);

SYNTAX ERROR

None
LISP: (* (car 4) 22);

SYNTAX ERROR

None
LISP: (+ 3 (car (cdr (cdr (cdr (1 2))))));
['NUM', ['+', ['num', 3.0], ['car', ['cdr', ['cdr', ['cdr', [['num', 1.0], [['num', 2.0], []]]]]]]]]

CDR of empty list Error!

LISP: exit;