Table of Contents

5. Functional data representation

5.1. Nats

Consider the following toy implementation of the type Nat which encodes natural numbers.

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

For instance, 3 will be encoded as the value: Succ(Succ(Succ(Zero))).

5.1.1. Write a function which implements addition over Nats:

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

5.1.2. Write a function which converts a Nat to an Int:

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

5.1.3. Write a function which converts an Int to a Nat.

def fromInt(i: Int): Nat

5.2. Binary Search Trees

In a binary search tree (BST), the key of the current node, is always:

Consider a binary search tree with keys as integers, encoded as follows:

trait ITree {}
case object Empty extends ITree 
case class INode(key: Int, left: ITree, right: ITree) extends ITree 

5.2.1. Create the tree shown below:

val tree = ???
/*
        5
      /   \
     2     7
    / \     \ 
   1  3      9 
*/

5.2.2. Implement the method size which determines the number of non-empty nodes from the BST.

5.2.3. Define the method contains, which checks if a given integer is a member of the BST.

5.2.4. Implement the method ins which inserts a new integer in the BST. Note: the insertion must return a new BST (the binary search tree property mentioned above must hold after insertion).

5.2.5. Implement a method flatten which converts a BST into a list of integers. You must carefully choose the flattening method in such a way as to obtain a sorted list from the BST. Hint: you may use the list concatenation operator ::: (triple colons; example usage: List(1,2,3):::List(4,5).

5.2.6. Implement a method depth which returns the maximal depth of a BST. Hint: use the method: _.max(_).

(!) 5.2.8. Implement a method minimum which returns the smallest integer from a BST. (If the tree is empty, we return -1). Hint: use the example above, to guide your implementation.

5.2.9. Implement a similar method maximum.

(!) 5.2.10. Implement a method successor(k) which returns the smallest integer from the BST, which is larger than k. Use the following examples for your implementation:

    5             t.successor(2) = 5                      
   / \            t.successor(5) = 6
  2   7           t.successor(7) = 8
     / \          
    6   8

(!!) 5.2.11. Implement a method remove(k) which removes element k from the BST.