From 87601a2e9c3fe2777b9f5b3f2be702998c167d5b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A9r=C3=A9my=20Zurcher?= Date: Thu, 25 Apr 2013 17:16:53 +0200 Subject: Scala : sandbox: Scala : add 6-natural --- Scala/sandbox/0-main.scala | 1 + Scala/sandbox/6-natural.scala | 33 +++++++++++++++++++++++++++++++++ 2 files changed, 34 insertions(+) create mode 100644 Scala/sandbox/6-natural.scala 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") + } +} -- cgit v1.1-2-g2b99