Lab 2
Lab 2
FileNew ProjectScala WizardsScala Project (ex. parsing2) When the project is opened, expand it until you see the src node. Right-click and select NewPackage (ex. listing1) Right-click on that package, select NewScala Application, input Lab2 In the newly created Scala object, complete the main method as follow package listing1 object Main { def main(args: Array[String]) { println("Hello") } }
Right-click and select the menu item "Run As Scala Application" to see the result Interpretation: You can see that a Scala program structure is very similar to Java one. It has package import, an object and then the main method (defined in Scala-ish way). The difference between Java and Scala is the object name (Main) doesnt have to be the same as file name (Lab2.scala).
In this step, we will try to create a binary tree in Scala using a special type of class in Scala, which facilitates the tree traverse very much using pattern matching, Case Class. Example:
trait SimpleTree // Leaf is a SimpleTree with an Int value only case class Leaf(value : Int) extends SimpleTree // Node is a SimpleTree includes two SimpleTree values on // its left and right case class Node(left : SimpleTree, right : SimpleTree) extends SimpleTree
For example, if we have an instance Node(Node(Leaf(3), Leaf(2)), Node(Leaf(7), Node(Leaf(6), Leaf(8)))) it will have an abstract tree like this
Now, write another instance based on an abstract tree with at least 4 nodes. (submit before the class) Step3: Pattern Matching
selectorExpr match { case pattern => expr ... case pattern => expr }
When we specify variables l, r, v as the arguments of a case class, it will be bound to the values in the case class instances; then, you can use them in the expressions. def sum(t : SimpleTree) : Int = t match { case Node(l, r) => sum(l) + sum(r) case Leaf(v) => v }
Matches are tried in order. To have an else case, use the wildcard pattern at the end case _ => exprToDoIfItDoesnotMatchAnyAbove
Traverse the recursive call of sum when it calculates the tree in the above example?
The Option Type
Option type expresses 0 or 1 relationship Case class with two cases: Some, None Example: List.find returns Option[A]. val result = lst.find(_ % 2 == 0) result match { case Some(x) => println(x) case None => println("No match") }
cay tieu bieu cho cu phap cua 1 chuong trinh hoac 1 phan chuong trinh
Tree that represents the syntax of a program (or a program part) Example: Expression tree for 5 - 6 * x
Co
Model in Scala: trait Expr case class case class case class f: (Int, Number(value : Int) extends Expr Variable(name : String) extends Expr Operator(left : Expr, right : Expr, Int) => Int) extends Expr
The above tree would be Operator(Number(5), Operator(Number(6), Variable("x"), _ * _), _ - _) Syntax Tree Evaluation
To compute value of expression, we need to assign values of free variables Use Map[String, Int] structure in Scala Scala immutable maps: o val map = Map(key1 -> value1, key2 -> value2) yields map with given key/value pairs o The + operator (map + (key3 -> value3)) extends map with new key/value pair o map(key) yields value of key (must exist) o map.get(key) yields Option, either Some(value) or None
def eval(expr : Expr, symbols : Map[String, Int]) : Int = expr match { case Number(num) => num case Variable(name) => symbols(name) case Operator(left, right, f) => f(eval(left, symbols), eval(right, symbols)) } To use eval to evaluate our expression tree with x=3, use eval(Operator(Number(5), Operator(Number(6), Variable("x"), _ * _), _ - _), Map("x" -> 3)
4. Create package listing2. Follow listing 2 to add the classes Expr, Number, Variable, Operator to the Main.scala file and add the eval method to the Main object. In the main method, construct the tree
+ Co
and evaluate it with a symbol table in which x is 5 and y is 7. What is the code of your Main.scala file? 5. (Simulating the Map structure in Scala) case class Symbol(variable: String, value: Int) Give a list of symbols List[Symbol], write a get function that return value of the given variable. Hint: Use find(). viet 1 function get tra ve gia tri cua E.g. val symbolList = List[Symbol("x", 5), Symbol("y", 7)] get(symbolList, "x") // yields 5 6. (Advanced) Define a class Poly that models a polynomial with one variable. Polynomials are defined according to these rules:
bien
A constant is a polynomial x is a polynomial The sum and product of two polynomials are polynomials
Define case classes Const, X, Sum, Prod and a function deriv(p : Poly) : Poly that computes the derivative of a polynomial. For example, val poly = deriv(Sum(Prod(X(),X()),X())) // i.e. x*x + x // sets poly to Sum(Sum(Prod(X(),Const(1.0)),Prod(Const(1.0),X())),Const(1.0)) // i.e. x*1+1*x+1 Do not simplify the result.