mon mon - 1 year ago 70
Scala Question

How to define a function inside match block


Is there a way to define the insert function inside the makeOrderedLeafList match block?


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)

Answer Source

Just place it inside the case before calling it:

scala> "hello" match {
 | case "hel" => 1
 | case "hello" =>
 |   def f(i: Int): Int = {
 |     i * 2
 |   }
 |   f(3) // don't forget to call the function...
 | }
res0: Int = 6

The right-hand side of a case expression can be any code block that returns the expected type. A code block can contain function definitions.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download