Presentation is loading. Please wait.

Presentation is loading. Please wait.

UMBC CMSC 331 Case Classes in Scala Intro. Basic Properties Case classes are regular classes which export their constructor parameters and which provide.

Similar presentations


Presentation on theme: "UMBC CMSC 331 Case Classes in Scala Intro. Basic Properties Case classes are regular classes which export their constructor parameters and which provide."— Presentation transcript:

1 UMBC CMSC 331 Case Classes in Scala Intro

2 Basic Properties Case classes are regular classes which export their constructor parameters and which provide a recursive decomposition mechanism via pattern matching. 2

3 Example 3 abstract class Term case class Var(name: String) extends Term case class Fun(arg: String, body: Term) extends Term case class App(f: Term, v: Term) extends Term

4 Code 4 Code Example For every case class the Scala compiler generates equals method which implements structural equality and atoString method. For instance and so... Fun("x", Fun("y", App(Var("x"), Var("y"))))

5 Results 5 val x1 = Var("x") val x2 = Var("x") val y1 = Var("y") println("" + x1 + " == " + x2 + " => " + (x1 == x2)) println("" + x1 + " == " + y1 + " => " + (x1 == y1)) Var(“x”) == Var(“x”) =>true Var(“x”) == Var(“y”) => false

6 Example object TermTest extends Application { def printTerm(term: Term) { term match { case Var(n) => print(n) case Fun(x, l, r) ) => print("^" + x + ".") printTerm(b) case App(f, v) => Console.print("(") printTerm(f) print(" ") printTerm(v) print(")") } …. abstract class Term case class Var(name: String) extends Term case class Fun(arg: String, body: Term) extends Term case class App(f: Term, v: Term) extends Term

7 Example Cont def isIdentityFun(term: Term): Boolean = term match { case Fun(x, Var(y)) if x == y => true case _ => false } val id = Fun("x", Var("x")) val t = Fun("x", Fun("y", App(Var("x"), Var("y")))) printTerm(t) println println(isIdentityFun(id)) println(isIdentityFun(t)) }

8 Another Example 8 abstract class IntTree case class Empty() extends IntTree case class Node(value: Int, left: IntTree, right:IntTree) extends IntTree

9 How would I add the Ints in such a Tree? object PlusTest extends Application { def plus(tree: IntTree) { tree match { case Empty => 0 case Node(value: Int, left: IntTree, right:IntTree) => value + plus(left) + plus(right) } abstract class IntTree case class Empty() extends IntTree case class Node(value: Int, left: IntTree, right:IntTree) extends IntTree

10 References 10 A tour of Scala : Traits (see http://www.scala- lang.org) Programming in Scala, Martin Odersky et al, Artima press 2009 Beginning Scala, David Pollak, Apress, 2009


Download ppt "UMBC CMSC 331 Case Classes in Scala Intro. Basic Properties Case classes are regular classes which export their constructor parameters and which provide."

Similar presentations


Ads by Google