Skip to content

Instantly share code, notes, and snippets.

@kaaloo
Created October 8, 2013 12:52
Show Gist options
  • Save kaaloo/6884209 to your computer and use it in GitHub Desktop.
Save kaaloo/6884209 to your computer and use it in GitHub Desktop.
A simplified model for the natural numbers (Peano numbers), from week 4 of Functional Programming in Scala
abstract class Nat {
def isZero: Boolean
def predecessor: Nat
def successor: Nat = new Succ(this)
def +(that: Nat): Nat
def -(that: Nat): Nat =
if (that.isZero)
this
else
predecessor - that.predecessor
}
object Zero extends Nat {
def isZero = true
def predecessor = throw new NoSuchElementException
def +(that: Nat) = that
}
class Succ(n: Nat) extends Nat {
def isZero = false
def predecessor = n
def +(that: Nat) = new Succ(n + that)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment