From Martin Oder’s Scala course, I have the following exercise (this is a video exercise that answers):
"Provide an implementation of the abstract class Nat, which represents non-negative integers
Do not use standard references in this implementation. Rather, implement a sub-object and subclass.
One for the number zero, the other for strictly saturated numbers. "
Here is the code:
abstract class Nat {
def isZero : scala.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 = throw new Error("0.predecessor")
def + (that: Nat) = that
def - (that: Nat) = if(that.isZero) this else throw new Error("negative number")
}
class Succ(n : Nat) extends Nat {
def isZero = false
def predecessor = n
def +(that : Nat) = new Succ(n + that)
def -(that: Nat) = n - that.predecessor
}
In the Scala sheet, I have:
object NatTests {
new Successor(Zero).+(new Successor(Zero))
}
Which brings back the new Suzerson. I don’t think I fully understand this code, so how can I add non-zero objects without a code extension? If so, how is this achieved?
source
share