Skip to content

Instantly share code, notes, and snippets.

@huseyinyilmaz
Created December 28, 2015 04:54
Show Gist options
  • Save huseyinyilmaz/44224825717a7d79a18b to your computer and use it in GitHub Desktop.
Save huseyinyilmaz/44224825717a7d79a18b to your computer and use it in GitHub Desktop.
Natural numbers implementation in scala
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 = error("no predecessor")
def + (that: Nat): Nat = that
def - (that: Nat): Nat =
if (that == Zero) this
else error("zero minus is not possible")
override def toString = "0"
}
class Succ(n: Nat) extends Nat{
def isZero = false
def predecessor= n
def - (that:Nat): Nat =
if (that == Zero) this
else this.predecessor - that.predecessor
def + (that:Nat): Nat =
if (that == Zero) this
else this.successor + that.predecessor
override def toString = "1+" ++ this.predecessor.toString
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment