summaryrefslogtreecommitdiffstats
path: root/Scala/sandbox
diff options
context:
space:
mode:
Diffstat (limited to 'Scala/sandbox')
-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")
+ }
+}