NOTE: Code required in Scala. No other language.
Question 4. Arithmetic expressions can be represented as operator trees. For example, the expression 1+2 (3+4) can be represented as the following tree:
*
/ \
/ \
/ \
+ +
/ \ / \
1 2 3 4
where the leaf nodes are numbers and the interior nodes specify an operation to perform. We will encode the nodes of the tree using a case class. This case class will store the operator ("*", "-", "/", "+", or a Double), a left child, and a right child. The operator is one of "*", "-", "/", "+" for internal nodes, but for leaves, the operator is simply a Double. Thus we need to use Either for operators. Since leaves do not have left or right children, we will need to use Option types for leaves. Our case class is then defined as follows:
case class Node(first: Option[Node], op: Either[String, Double], second: Option[Node])
"first" refers to the left child, "op" is the operator, and "second" is the right child. For example, the leftmost leaf in the tree above just contains the number 1. We can define its corresponding node as follows:
val leaf1 = Node(None, Right(1.0), None)
because it doesn't have any children (hence the None) and "op" field should be 1.0 (since Double is the Right type of Either[String, Double], we use Right(1.0)).
Similarly, the leaf nodes 2, 3, and 4 can be created as follows:
val leaf2 = Node(None, Right(2.0), None)
val leaf3 = Node(None, Right(3.0), None)
val leaf4 = Node(None, Right(4.0), None)
The two intermediate nodes that hold "+" can be created as:
val inner1 = Node(Some(leaf1), Left("+"), Some(leaf2))
val inner2 = Node(Some(leaf3), Left("*"), Some(leaf4))
and the root node:
val root = Node(Some(inner1), Left("*"), Some(inner2))
Your job is to write the function "evaluate" whose input is a parameter called "r" and its type is Node. When we pass in a node of an operator tree, the function should evaluate the expression corresponding to that node and return the result. For example, for the nodes we defined, we should get the following results:
evaluate(leaf1) should return 1.0
evaluate(leaf3) should return 3.0
evaluate(inner1) should return 3.0
evaluate(root) should return 21.0
This function should be recursive and should use pattern matching.