Question: Using F# language. Complete answer in order to get full credit. Do not copy-paste from diferent site. Thank you Interpreter 0 In this problem, we
Using F# language. Complete answer in order to get full credit. Do not copy-paste from diferent site. Thank you
Interpreter 0 In this problem, we begin our exploration of the use of F# for language-oriented programming. You will 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).
Rather than working directly with the concrete syntax above, we will imagine that we have a parser that parses input into an abstract syntax tree, as is standard in real compilers. Hence your interpreter will take an input of the following discriminated union type:
type Exp = Num of int | Neg of Exp | Sum of Exp * Exp | Diff of Exp * Exp | Prod of Exp * Exp | Quot of Exp * Exp
Note how this definition mirrors the grammar given above. For instance, the constructor Num makes an integer into an Exp, and the constructor Summakes a pair of Exp's into an Exprepresenting their sum. Interpreting abstract syntax trees is much easier than trying to interpret concrete syntax directly. Note that there is no need for a constructor corresponding to parentheses, as the example given above would simply be represented by
Prod(Num 3, Diff(Num 5, Num 1))
which represents the parse tree which looks like
Your job is to write an F# function evaluatethat takes an abstract syntax tree and returns the result of evaluating it. Most of the time, evaluating a tree will produce an integer, but we must address the possibility of dividing by zero. This could be handled by raising an exception, but instead we choose to make use of the built-in F# type
type 'a option = None | Some of 'a
Thus evaluate will have type Exp -> int option, allowing it to return Some m in the case of a successful evaluation, and Nonein 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
Naturally, evaluate e should use recursion to evaluate each of e's sub-expressions; it should also use match to 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 | ...
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
