Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You <em>are</em> able to add non zero numbers / objects without extending any of the classes <code>Nat</code>, <code>Zero</code>, or <code>Succ</code>. When you use an object <code>natObj</code> of type <code>Nat</code> and construct a new object <code>new Succ(natObject)</code> that new object represents a number that is one higher than the number that <code>natObj</code> represents. </p> <p>Maybe being able to view the objects, makes this a bit clearer:</p> <pre><code>abstract class Nat { def isZero : 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") override def toString = "0 =&gt; Zero" } class Succ(n : Nat) extends Nat { def isZero = false def predecessor = n def + (that : Nat) = new Succ(n + that) def - (that: Nat) = if (that.isZero) this else n - that.predecessor override def toString = { def findNumber(nat: Nat): Int = if (nat.isZero) 0 else 1 + findNumber(nat.predecessor) val number = findNumber(this) String.valueOf(number) + " =&gt; " + ((1 to number) fold ("Zero")) ( (s,_) =&gt; "Succ(" + s + ")") } } </code></pre> <p>Now your Scala worksheet will show you the number an object represents and its internal structure:</p> <pre><code>object NatTests extends App { val nat0 = Zero val nat1 = new Succ(Zero) val nat2 = new Succ(nat1) // or new Succ(new Succ(Zero)) val nat3 = new Succ(nat2) // or new Succ(new Succ(new Succ(Zero))) println(nat0) //&gt; 0 =&gt; Zero println(nat1) //&gt; 1 =&gt; Succ(Zero) println(nat2) //&gt; 2 =&gt; Succ(Succ(Zero)) println(nat3) //&gt; 3 =&gt; Succ(Succ(Succ(Zero))) println(nat2 + nat2) //&gt; 4 =&gt; Succ(Succ(Succ(Succ(Zero)))) println(nat3 + nat2) //&gt; 5 =&gt; Succ(Succ(Succ(Succ(Succ(Zero))))) } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload