functional programming – Trying to understand how this class representation truly represents Natural numbers in Scala


Following Martin Odersky’s course on coursera – Functional Programming with Scala and I’m on Week 4 where we’re learning about Types and Pattern Matching. In the video lecture, this is the representation of a Natural Number:

abstract class Nat {
  def isZero: Boolean
  def predecessor: Nat
  def successor: Nat = new Succ(this)
  def + (that: Nat): Nat
  def - (that: Nat): Nat = if (that.isZero) this else (predecessor - that.predecessor)
}

object Zero extends Nat { // for a zero
  def isZero = true
  def predecessor = throw new NoSuchElementException
  def + (that: Nat) = that
}
class Succ(n: Nat) extends Nat { // for non-zero (positive) numbers
  def isZero = false
  def predecessor = n
  def + (that: Nat) = n + that.successor
}

My questions are:

  1. when I create a val two = new Succ(2) why would I set the two.predecessor = 2 when 2‘s predecessor is actually 1?

  2. When I call two + new Succ(4) internally why am I evaluating 2 + successor of 4 and not new Succ(2 + 4)?

  3. In the main abstract class Nat, the successor field is intialised with a Succ object. Wouldn’t the value of successor be the same as the object that was just constructed?

I’m just …unable to grasp the relationship/implementation here …

PS – I do have a Java background if that helps