diff options
Diffstat (limited to 'Scala/sandbox/6-natural.scala')
-rw-r--r-- | Scala/sandbox/6-natural.scala | 33 |
1 files changed, 33 insertions, 0 deletions
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") + } +} |