I am looking to build an evaluation tree, for starters, for arithmetic expressions.
I have the following case classes defined:
abstract class Expr
case class Num(n: Integer) extends Expr
case class Plus(e1: Expr, e2: Expr) extends Expr
My parser, when it sees the expression 1 + 1 + 1 produces the following tree:
Plus(Plus(Num(1), Num(1)), Num(1))
I then have the following data type defined:
case class Tree[Expr](e: Expr, children: List[Tree[Expr]])
Here is a badly drawn evaluation tree:
Num(1) Num(1)
----------------------------
Plus(Num(1), Num(1)) Num(1)
---------------------------------------
Plus(Plus(Num(1),Num(1)), Num(1))
I want to build up a tree data structure representing that. So, the resulting output of evaluation would be:
Tree(
Plus(Plus(Num(1), Num(1)), Num(1)),
List(Tree(Plus(Num(1),Num(1),
List(Tree(Num(1), List()),
Tree(Num(1), List()))),
Tree(Num(1), List())))
I want to have a method eval:
def eval(e: Expr, t: Tree[Expr]): Tree[Expr] = (e, t) match {
// Do the matching on Num
case Num(n) ........ =>
case Plus(e1, e2) ...... =>
}
Is it the right way to represent this evaluation tree and if so, how can I go about creating such a nested tree data structure.
EDIT: Here is a method eval for addition only
def eval(e: Expr): Tree[Expr] = e match {
case Num(n) => Tree(Num(n), Nil)
case Plus(e1, e2) => Tree(Plus(e1, e2), List(eval(e1), eval(e2)))
}