summaryrefslogtreecommitdiffstats
path: root/Scala
diff options
context:
space:
mode:
authorJérémy Zurcher <jeremy@asynk.ch>2013-04-25 17:16:53 +0200
committerJérémy Zurcher <jeremy@asynk.ch>2016-11-10 18:03:23 +0100
commit87601a2e9c3fe2777b9f5b3f2be702998c167d5b (patch)
tree7a2c7f7e15a84ddafb6f8c197f5c6003574e028a /Scala
parent5843d3d60332e52fec2977cfcff6735ba0b8c76e (diff)
downloadcoursera-87601a2e9c3fe2777b9f5b3f2be702998c167d5b.zip
coursera-87601a2e9c3fe2777b9f5b3f2be702998c167d5b.tar.gz
Scala : sandbox: Scala : add 6-natural
Diffstat (limited to 'Scala')
-rw-r--r--Scala/sandbox/0-main.scala1
-rw-r--r--Scala/sandbox/6-natural.scala33
2 files changed, 34 insertions, 0 deletions
diff --git a/Scala/sandbox/0-main.scala b/Scala/sandbox/0-main.scala
index 2092d9d..99ee4ba 100644
--- a/Scala/sandbox/0-main.scala
+++ b/Scala/sandbox/0-main.scala
@@ -8,5 +8,6 @@ object Main extends App {
Rationals.run
IntSet.run
IntList.run
+ Natural.run
}
diff --git a/Scala/sandbox/6-natural.scala b/Scala/sandbox/6-natural.scala
new file mode 100644
index 0000000..01af1be
--- /dev/null
+++ b/Scala/sandbox/6-natural.scala
@@ -0,0 +1,33 @@
+// Peano numbers
+object Natural
+{
+ abstract class Nat
+ {
+ def isZero: Boolean
+ def predecessor: Nat
+ def successor = new Succ(this)
+ def + (that: Nat): Nat
+ def - (that: Nat): Nat
+ }
+
+
+ object Zero extends Nat
+ {
+ def isZero = true
+ def predecessor = throw new Error("0.predecessor")
+ def + (that: Nat) = that
+ def - (that: Nat) = if (that.isZero) this else throw new Error("negative number")
+ }
+
+ class Succ(n: Nat) extends Nat
+ {
+ def isZero = false
+ def predecessor = n
+ def + (that: Nat) = new Succ(n + that)
+ def - (that: Nat) = if (that.isZero) this else n - that.predecessor
+ }
+
+ def run = {
+ println("Natural")
+ }
+}