CS 152 - Lecture 8

Cover page image

Cay S. Horstmann

Scala Classes

Construction Parameters

Scala Objects

Case Classes

Pattern Matching

Syntax Trees

Syntax Tree Evaluation

Functions with Variable Arguments

Lab

???

Step 1

Add the classes Expr, Number, Variable, Operator to a Main.scala file, inside a Main object. Add the eval method to the Main object. In the body of the Main object, construct the tree

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

Step 2

Now we want to process 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 : Expr)

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
System.out.println(sym2)

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

Note: This eval method requires you to call the eval method that we defined for expressions, but it is a different method—it consumes a definition and a symbol table, yielding another symbol table.