Created
October 8, 2013 12:52
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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