This is an old revision of the document!
Lab 4. Algebraic Datatype definition
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 = ???
4.2. The type IList (list over integers)
Consider the following type defined to represent lists of integers:
trait IList case object Void extends IList case class Cons(x: Int, xs: IList) extends IList
4.2.1. Implement isEmpty
which checks if a list is empty:
def isEmpty(l: IList): Boolean = ???
4.2.2. Implement size
which returns the size of the list:
def size(l: IList): Int = ???
4.2.3. Implement append
which concatenates two lists:
def append(l1: IList, l2: IList): IList = ???
4.2.4. (!) Implement last
which returns the last element from a list:
def last(l: IList): Int = ???
4.2.5. (!) Implement reverse
. There are two different ways to implement reverse (with direct and with tail-end recursion). Try both implementations.
def reverse(l: IList): IList = ???
4.2.6. Implement contains
which checks if an element is a member of a list.
def contains(e: Int, l: IList): IList = ???
4.2.7. Implement max
which returns the largest integer from a list:
def max(l: Ilist): IList = ???
4.2.8. Implement isSorted
which checks if a list is sorted:
def isSorted(l: IList): IList = ???
4.2.9. Implement merge
which merges two sorted lists:
def merge(l1: IList, l2: IList): IList = ???
4.2.10. Implement mergeSort
which sorts a list:
def mergesort(l: IList) IList = ???