Edit this page Backlinks This page is read only. You can view the source, but not change it. Ask your administrator if you think this is wrong. ====== Lab 5. Functional vs Object-Oriented decomposition ====== ==== 4.1. The type Nat ===== Consider the following type defined to represent natural numbers: <code scala> trait Nat case object Zero extends Nat case class Succ(n: Nat) extends Nat </code> **4.1.1.** Implement the following function: <code scala> def isZero(n: Nat): Nat = n match { case Zero => ??? case Succ(np) => ??? } </code> **4.1.2.** Implement the addition function over natural numbers: <code scala> def add(n: Nat, m: Nat): Nat = n match { case Zero => ??? case Succ(np) => ??? } </code> **4.1.3.** Implement the subtraction function over natural numbers. If $math[n > m] then $math[m - n = 0]. <code scala> def subtract(n: Nat, m: Nat): Nat = ??? </code> **4.1.4.** Implement ''greater'' which checks if a natural number is strictly larger than the other: <code scala> def greater(n: Nat, m: Nat): Nat = (n,m) match { ??? } </code> **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: <code scala> def equal(n: Nat, m: Nat): Nat = ??? </code> **4.1.6.** Implement a function which converts a Nat to a Scala Int: <code scala> def toInt(n: Nat): Int = ??? </code> **4.1.7.** Implement a function which converts an Int to a Nat: <code scala> def fromInt(i: Int): Nat = ??? </code>