Question: In the language Lisp, each of the four basic arithmetic operators appears before an arbitrary number of operands, which are separated by spaces. The resulting

In the language Lisp, each of the four basic arithmetic operators appears before an arbitrary number of operands, which are separated by spaces. The resulting expression is enclosed in parentheses. The operations behave as follows.

(+ a b c ) returns the sum of all operands, and (+) returns 0.

(- a b c ) returns a-b-c- and (- a) returns a. The minus operator must have at least one operand.

(* a b c ) returns the product of all the operands, and (*) returns 1.

(/ a b c ) returns a/b/c/ and (/ a) returns 1 / a. The divide operator must have at least one operand.

You can form larger arithmetic expressions by combining these basic expressions using a fully parenthesized prefix notation. For example, the following is a valid Lisp expression:

(+ (- 6) (* 2 3 4) (/ (+ 3) (*) (- 2 3 1)))

The expression is successively evaluated as follows:

(+ -6 24 (/ 3 1 -2))

(+ -6 24 -1.5)

16.5

Design and implement an algorithm that uses a stack to evaluate a legal Lisp expression composed of the four basic operators and integer values. Write a main program (LispEvaluator.java) that reads such an expression and demonstrates your algorithm.

Sample inputs and outputs

(+ 5 0 10) evaluates to 15.0

(+ 5 0 10 (- 7 2)) evaluates to 20.0

(+ (- 6) (* 2 3 4) (/ (+ 3) (*) (- 2 3 1))) evaluates to 16.5

(+ (- 632) (* 21 3 4) (/ (+ 32) (*) (- 21 3 1))) evaluates to -378.11764705882354

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!