blob: 36beb68698d50ea2b5bb7f49dc574c2d8940d820 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
|
object PatternMatching
{
trait Expr {
def eval: Int = this match {
case Number(n) => n
case Sum(e1, e2) => e1.eval + e2.eval
}
def show: String = this match {
case Number(n) => n.toString
case Sum(e1, e2) => e1.show + " + " + e2.show
}
}
case class Number(n: Int) extends Expr
case class Sum(e1: Expr, e2: Expr) extends Expr
def eval1(e: Expr): Int = e match {
case Number(n) => n
case Sum(e1, e2) => eval1(e1) + eval1(e2)
}
def run = {
println("PatternMatching")
println( eval1(Sum(Number(1), Number(2))) )
val e = Sum(Number(1), Number(2))
println( e.show + " = " + e.eval )
}
}
|