UMBC CMSC 331 Case Classes in Scala Intro
Basic Properties Case classes are regular classes which export their constructor parameters and which provide a recursive decomposition mechanism via pattern matching. 2
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 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"))))
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
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
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)) }
Another Example 8 abstract class IntTree case class Empty() extends IntTree case class Node(value: Int, left: IntTree, right:IntTree) extends IntTree
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
References 10 A tour of Scala : Traits (see lang.org) Programming in Scala, Martin Odersky et al, Artima press 2009 Beginning Scala, David Pollak, Apress, 2009