Skip to content

Instantly share code, notes, and snippets.

@nicola88
Last active March 21, 2019 16:29
Show Gist options
  • Select an option

  • Save nicola88/130f46898192e9473ae8d4c43c4aa750 to your computer and use it in GitHub Desktop.

Select an option

Save nicola88/130f46898192e9473ae8d4c43c4aa750 to your computer and use it in GitHub Desktop.
w5
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