This is an old revision of the document!


Lab 5. Functional vs Object-Oriented decomposition

4.1. The type Nat

Consider the following type defined to represent natural numbers:

trait Nat 
case object Zero extends Nat
case class Succ(n: Nat) extends Nat

4.1.1. Implement the following function:

def isZero(n: Nat): Nat = 
   n match {
       case Zero => ???
       case Succ(np) => ???
   }

4.1.2. Implement the addition function over natural numbers:

def add(n: Nat, m: Nat): Nat = 
   n match {
       case Zero => ???
       case Succ(np) => ???
   }

4.1.3. Implement the subtraction function over natural numbers. If $ n > m$ then $ m - n = 0$ .

def subtract(n: Nat, m: Nat): Nat = ???

4.1.4. Implement greater which checks if a natural number is strictly larger than the other:

def greater(n: Nat, m: Nat): Nat = 
   (n,m) match {
      ???
   }

4.1.5. Equality is already defined for all case classes, as structural equality (objects built in the same way are equal). However, re-implement equality over naturals:

def equal(n: Nat, m: Nat): Nat = ???

4.1.6. Implement a function which converts a Nat to a Scala Int:

def toInt(n: Nat): Int = ???

4.1.7. Implement a function which converts an Int to a Nat:

def fromInt(i: Int): Nat = ???