Created
December 28, 2015 04:54
-
-
Save huseyinyilmaz/44224825717a7d79a18b to your computer and use it in GitHub Desktop.
Natural numbers implementation 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 = 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