Question
Write an F# program to evaluate arithmetic expressions written in the language given by the following context-free grammar: E -> n | -E | E
Write an F# program to evaluate arithmetic expressions written in the language given by the following context-free grammar:
E -> n | -E | E + E | E - E | E * E | E / E | (E)
In the above, n is an integer literal, -E is the negation of E, the next four terms are the sum, difference, product, and quotient of expressions, and (E) is used to control the order of evaluation of expressions, as in the expression 3*(5-1).
(1) Use F# type definition (discriminated union type) to define an abstract syntax tree grammar based on the above concrete grammar by completing the following partial solution:
type Exp = Num of int| Prod of Exp * Exp | ...
(hint: add one constructor in the discriminated union type for each rule. No constructor is needed for the parentheses rule). The example given above would simply be represented by
2
Prod(Num 3, Diff(Num 5, Num 1)).
(2) To deal with possible division by zero, we make use of the built-in F# type in our evaluate function:
type 'a option = None | Some of 'a
evaluate returns Some n in the case of a successful evaluation, and None in the case of an evaluation that fails due to dividing by zero. For example,
> evaluate (Prod(Num 3, Diff(Num 5, Num 1)));;
val it : int option = Some 12
> evaluate (Diff(Num 3, Quot(Num 5, Prod(Num 7, Num 0))));;
val it : int option = None
(3) Write a recursive function evaluate to evaluate arithmetic expressions defined using the type definitions in (1) & (2). evaluate e should use pattern matching based on the discriminated union type to evaluate each of e's sub-expressions; it should also distinguish between the cases of successful or failed sub-evaluations. To get you started, here is the beginning of the definition of evaluate:
let rec evaluate = function
| Num n -> Some n
| Neg e -> match evaluate e with
| Some n -> Some (-n)
| None -> None
| Sum (e1, e2) -> match (evaluate e1, evaluate e2) with
|...
| ...
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started