Question: Write a function called evaluate, which takes a well - formed binary tree ( constructed using your build _ tree ( 1 0 ) function
Write a function called evaluate, which takes a wellformed binary tree constructed using your buildtree
function and returns the numeric result of evaluating the arithmetic expression represented by the tree.
Examples:
let t buildtree ;;
let v evaluate t;; v should be the int value
Test Cases:
Integer Arithmetic Expression:
Pass an integer arithmetic expression eg to buildtree to construct the tree.
Then pass the tree to evaluate, which should return the final integer result eg
Float Arithmetic Expression:
Pass a float arithmetic expression eg to buildtree.
Pass the tree to evaluate, which should return the final float result eg
Preconditions:
The input tree is wellformed, created using the buildtree function.
The operators in the tree are valid for the corresponding numeric types eg for integers, for
floats
Postconditions:
If the tree represents a valid arithmetic expression, the function returns the computed numeric
value.
The result will be an integer or float, depending on the type of the arithmetic expression.
reduce these expressions up to a certain point.
The expressions will only involve addition and multiplication. But now, we distinguish between constants
and variables. The goal is to write a function that reduces expressions using basic rules like x x
x x etc. If variables are involved, reductions will eventually lead to a stuck state. If there are
no variables, then the reductions will go all the way to a single numeric value.
Example:
type expr
Const of int
Var of string
Add of expr expr
Mul of expr expr;;
Your task is to write a function called reduce, which takes a single expr and reduces it as much as
possible by recursive application of reduction rules to the input expression. Test with cases like:
reduce Add Const Var x;; should return Var x
reduce Mul Const Var y;; should return Var y
reduce Mul Const Add Const Const ;; should return Const
For the actual integer addition and multiplication within your reduction process, you should simply use
OCamls internal and operators, respectively.
Step by Step Solution
There are 3 Steps involved in it
1 Expert Approved Answer
Step: 1 Unlock
Question Has Been Solved by an Expert!
Get step-by-step solutions from verified subject matter experts
Step: 2 Unlock
Step: 3 Unlock
