Question: Write a function called build _ tree that constructs a binary tree from a fully parenthesized arithmetic ( 1 0 ) expression using numeric operands

Write a function called build_tree that constructs a binary tree from a fully parenthesized arithmetic (10)
expression using numeric operands and operators.
OCaml does not perform automatic type conversions, even if there is no loss of information. For example,
if will not automatically convert the integer 2 to the float 2.0. This, however, makes it less user-friendly
than many other languages. Your implementation must perform such type conversions so that the user
is able to write expressions like 1.5+.2. You are not expected to overload operators, however. Your
only job here is to make sure that if the user mixes up integers and floats, then any integer is converted to
a float (e.g.,2 becomes 2.0 if the user input is 1.5+.2; 1 and 2 both become 1.0 and 2.0, respectively,
if the user input is 1+.2).
As such, the lossless type conversion from int to float is done internally by your method. The end-user
remains abstracted away from this detail.
The function takes one argument:
An arithmetic expression, which may involve integers or floating-point numbers and their corre-
sponding operators.
Examples:
build_tree (1+(2*4)) should create a tree representing this expression.
build_tree ((1.5+.0.75)-.0.25) should create a tree for the floating-point expression.
Assumptions:
The input expression is fully parenthesized, including the outermost parentheses.
Operators are separated from their operands by a single space (e.g.,1.5*.2.0).
The operators provided are valid for the type of operands (e.g.,+ for integers, +. for floats).
Preconditions:
The input expression is fully parenthesized.
The expression has correctly placed spaces between operands and operators.
The operators provided by the user are valid for the numeric type used in the expression.
Postconditions:
The function will return a binary tree where the internal nodes represent the arithmetic operators,
and the leaf nodes represent the numeric operands.
If the input expression is invalid (e.g., missing parentheses, invalid spacing, or incompatible opera-
tors), the function should return an error or raise an exception.
4. Write a function called evaluate, which takes a well-formed binary tree (constructed using your build_tree (10)
function) and returns the numeric result of evaluating the arithmetic expression represented by the tree.

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 Programming Questions!