Last active
March 21, 2019 16:29
-
-
Save nicola88/130f46898192e9473ae8d4c43c4aa750 to your computer and use it in GitHub Desktop.
w5
This file contains hidden or 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 | |
| def +(that: Nat): Nat | |
| def -(that: Nat): Nat | |
| } | |
| object Zero extends Nat { | |
| def isZero: Boolean = true | |
| def predecessor: Nat = throw new NoSuchElementException() | |
| def successor: Nat = new Succ(this) | |
| def +(that: Nat): Nat = that | |
| def -(that: Nat): Nat = | |
| if (that.isZero) Zero else throw new NoSuchElementException() | |
| override def toString(): String = "zero" | |
| } | |
| class Succ(n: Nat) extends Nat { | |
| def isZero: Boolean = false | |
| def predecessor: Nat = n | |
| def successor: Nat = new Succ(this) | |
| def +(that: Nat): Nat = | |
| n + that.successor | |
| def -(that: Nat): Nat = | |
| if (that.isZero) this else n - that.predecessor | |
| override def toString(): String = predecessor + "->*" | |
| } | |
| val one = new Succ(Zero) | |
| val two = new Succ(one) | |
| val three = new Succ(two) | |
| println(three + two) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment