summaryrefslogtreecommitdiffstats
path: root/Scala/sandbox/6-natural.scala
blob: 01af1befbd8f643d972899b12ad0ff30de0701e4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
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")
  }
}