This is an old revision of the document!


Lab 06. Datatypes in Scala

Consider the following implementation of a simple datatypes to encode natural number:

trait Nat {}
case object Zero extends Nat {}
case class Succ(n: Nat) extends Nat {}
 
val three = Succ(Succ(Succ(Zero)))

Write a function which converts a Nat into an Int:

def toInt(n: Nat): Int =
  n match {
    case Zero => ???
    case Succ(n) => ???
  }

Write a function which converts a positive Int into a Nat:

def fromInt(i: Int): Nat = ???
trait ITree {
  def contains (k: Int) : Boolean
  def ins (k: Int) : ITree
  def flatten: List[Int]
}