Parsing 1

Case Classes

Pattern Matching

The Option Type

Syntax Trees

Syntax Tree Evaluation

IDE Survey

Scala IDE Plugin

Scala in Eclipse

Lab

???

Step 1

Add the classes ExprTree, Number, Variable, Operator to the Main.scala file. Add the eval method to the Main object. In the main method, construct the tree

and evaluate it with a symbol table in which x is 5. What is the code of your Main.scala file?

If you didn't install Eclipse and the Scala plugin before class, then write the file with a text editor (in a lab9 subdirectory to match the package name) and compile/run with

scalac lab9/Main.scala
scala lab9.Main

Step 2

Now we want to add variable definitions (which we will write as val x = expr in the next lecture). For now, we will assume that they are already parsed into instances of

case class Definition(name : String, expr : ExprTree)

For example, a definition val x = 2 would be a Definition("x", Number(2)). A definition changes the symbol table. In a functional setting, that means we need to return a new table that contains all bindings in the old table and the new binding. For example,

val def1 = Definition("x", Number(2))
val def2 = Definition("y", Variable("x"))
val sym0 = Map[String, Int]()
val sym1 = eval(def1, sym0) // "x" -> 2
val sym2 = eval(def2, sym1) // "x" -> 2, "y" -> 2

Implement this eval method . What is the code of your method? (You can get the fields of a definition as defi.name, defi.expr.)