Case Classes in Scala Intro UMBC CMSC 331
Case Classes in Scala Intro UMBC CMSC 331
Basic Properties 2 Case classes are regular classes which export their constructor parameters and which provide a recursive decomposition mechanism via pattern matching.
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
Code 4 Code Example Fun("x", Fun("y", App(Var("x"), Var("y")))) For every case class the Scala compiler generates equals method which implements structural equality and ato. String method. For instance and so. . .
Results 5 val x 1 = Var("x") val x 2 = Var("x") val y 1 = Var("y") println("" + x 1 + " == " + x 2 + " => " + (x 1 == x 2)) println("" + x 1 + " == " + y 1 + " => " + (x 1 == y 1)) Var(“x”) == Var(“x”) =>true Var(“x”) == Var(“y”) => false
Example object Term. Test extends Application { def print. Term(term: Term) { term match { case Var(n) => print(n) abstract class Term case Fun(x, l, r) ) => case class Var(name: String) extends Term print("^" + x + ". ") case class Fun(arg: String, body: Term) extends Term print. Term(b) case class App(f: Term, v: Term) extends Term case App(f, v) => Console. print("(") print. Term(f) print(" ") print. Term(v) print(")") } ….
Example Cont def is. Identity. Fun(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")))) print. Term(t) println(is. Identity. Fun(id)) println(is. Identity. Fun(t)) }
Another Example 8 abstract class Int. Tree case class Empty() extends Int. Tree case class Node(value: Int, left: Int. Tree, right: Int. Tree) extends Int. Tree
How would I add the Ints in such a Tree? object Plus. Test extends Application { def plus(tree: Int. Tree) { tree match { case Empty => 0 case Node(value: Int, left: Int. Tree, right: Int. Tree) => value + plus(left) + plus(right) } } abstract class Int. Tree case class Empty() extends Int. Tree } case class Node(value: Int, left: Int. Tree, right: Int. Tree) extends Int. Tree
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
- Slides: 10