Skip to content

Instantly share code, notes, and snippets.

@bmarcot
Last active December 16, 2015 08:08
Show Gist options
  • Save bmarcot/5403292 to your computer and use it in GitHub Desktop.
Save bmarcot/5403292 to your computer and use it in GitHub Desktop.
// Peano numbers
abstract class Nat {
def isZero: Boolean
def predecessor: Nat
def successor: Nat = 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 is negative")
def + (that: Nat) = that
def - (that: Nat) = if (that.isZero) this else throw new Error("0.- is negative")
}
class Succ(n: Nat) extends Nat {
def isZero = false
def predecessor = n
def + (that: Nat) = this.predecessor + that.successor
def - (that: Nat) = if (that.isZero) this else this.predecessor - that.predecessor
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment