Lab 2

Download as pdf or txt
Download as pdf or txt
You are on page 1of 7

Lab 2

Lexical Analysis and Parsing


1. Use Scala Regex Library to find all match: a) C line comments, i.e. //. Ex: // this is a line comment b) An identifier is a sequence of letter, digit or underscore but the first character cannot be a digit. In addition, when the first character of an identifier is an underscore, the second character cannot be a underscore or a lowercase letter. Ex: _Abc xehs u34 u_2 "2'15s, 3'15s, 4'22s" Yield List(List(2, 3, 4), List(15, 15, 22)) 2. Given a string s, write a function that return s, so that: all symbols + in s are replaced by keyword add and all symbols - are replaced by keywords minus in s. For example, 3 + 4 - 5 3 add 4 minus 5 3. We continue the exercises after reading carefully some listings below. Have fun! __123 _abc 1abd c) Integers show how many minutes and how many seconds

LISTING 1: Case class and pattern matching


Step 1: Create new Scala Applications in Eclipse

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).

Step 2: Add Case Classes


case class ClassName(field1 : Type1, field2 : Type2, ...) extends Superclass

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:

Binary tree with values only in the leaves

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

Construct instances with ClassName(arg1, arg2, ...)

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

nhieu truong hop cho gia tri mau


Many possibilities for the patterns; in this part, we care about case class patterns // tree is an instance of // SimpleTree tree match { case Node(l, r) => expr1 case Leaf(v) => expr2 }

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

LISTING 2: Parse Trees

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:

dua theo kien truc map trong scala

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.

You might also like