summaryrefslogtreecommitdiffstats
path: root/Scala/sandbox
diff options
context:
space:
mode:
authorJérémy Zurcher <jeremy@asynk.ch>2013-04-28 00:08:00 +0200
committerJérémy Zurcher <jeremy@asynk.ch>2016-11-10 18:03:23 +0100
commit765ddc9e51305d6ba703666f42e67ae3fcc91058 (patch)
tree8ea500a737d8b80f3219a87aeea195ca461a6c09 /Scala/sandbox
parent82dc27578a2f57646f5b8c678699980b29b89c11 (diff)
downloadcoursera-765ddc9e51305d6ba703666f42e67ae3fcc91058.zip
coursera-765ddc9e51305d6ba703666f42e67ae3fcc91058.tar.gz
Scala : sandbox Scala : add 8-pattern-matching
Diffstat (limited to 'Scala/sandbox')
-rw-r--r--Scala/sandbox/0-main.scala1
-rw-r--r--Scala/sandbox/8-pattern-matching.scala29
2 files changed, 30 insertions, 0 deletions
diff --git a/Scala/sandbox/0-main.scala b/Scala/sandbox/0-main.scala
index 6f0edf3..b68b57e 100644
--- a/Scala/sandbox/0-main.scala
+++ b/Scala/sandbox/0-main.scala
@@ -10,5 +10,6 @@ object Main extends App {
IntList.run
Natural.run
Variance.run
+ PatternMatching.run
}
diff --git a/Scala/sandbox/8-pattern-matching.scala b/Scala/sandbox/8-pattern-matching.scala
new file mode 100644
index 0000000..36beb68
--- /dev/null
+++ b/Scala/sandbox/8-pattern-matching.scala
@@ -0,0 +1,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 )
+ }
+}