Question
Is there a way to define the insert function inside the makeOrderedLeafList match block?
Problem
Since insert function is only used in makeOrderedLeafList, I would like to define it inside it. However, if placed at the bottom, an error "Unit required". Cannot place at the top as "case" is being expected.
def makeOrderedLeafList(freqs: List[(Char, Int)]): List[Leaf] = freqs match {
case List() => List()
case h :: t => insert(h, makeOrderedLeafList(t))
case _ => throw new IllegalStateException
}
//--------------------------------------------------------------------------------
// Insert Leaf in the sorted list of Leaf.
//--------------------------------------------------------------------------------
def insert(c: (Char, Int), list: List[Leaf]): List[Leaf] = list match {
case List() => List(new Leaf(c._1, c._2))
case h :: t => {
//--------------------------------------------------------------------------------
// If C:[char, counter] is smaller, prepend it to the List[Leaf].
// Otherwise, recurse call insert to find a position in the tail of the list.
//--------------------------------------------------------------------------------
if (c._2 <= h.weight) new Leaf(c._1, c._2) :: list
else h :: insert(c, t)
}
}