Advertisement
zinch

Natural numbers impl

Dec 28th, 2016
330
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Scala 0.84 KB | None | 0 0
  1. package idealized.scala
  2.  
  3. abstract class Nat {
  4.   def isZero: scala.Boolean
  5.   def predecessor: Nat
  6.   def successor: Nat = new Succ(this)
  7.   def + (that: Nat): Nat
  8.   def - (that:Nat): Nat
  9. }
  10.  
  11. object Zero extends Nat {
  12.   override def isZero: scala.Boolean = true
  13.  
  14.   override def predecessor: Nat = throw new UnsupportedOperationException
  15.  
  16.   override def +(that: Nat): Nat = that
  17.  
  18.   override def -(that: Nat): Nat = if (that.isZero) this else throw new UnsupportedOperationException
  19.  
  20.  
  21.   override def toString = "0"
  22. }
  23.  
  24. class Succ(n: Nat) extends Nat {
  25.   override def isZero: scala.Boolean = false
  26.  
  27.   override def predecessor: Nat = n
  28.  
  29.   override def +(that: Nat): Nat = new Succ(n + that)
  30.  
  31.   override def -(that: Nat): Nat = if (that.isZero) this else n - that.predecessor
  32.  
  33.   override def toString = "s(" + predecessor.toString + ")"
  34. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement