Simple Scala Methods for finding Sum and Maximum

I am learning Scala. I have been confronted with the simple task of creating functions for finding the sum and maximum in the list of numbers. A precondition is that both functions should be solved recursively.

There are at least two different ways how to solve each function. First, I tried to come up with a recursive approach in the purest possible form.

Sum function

def sum(xs: List[Int]): Int = {
     if (xs.isEmpty) {
          0
     } else {
          xs.head + sum(xs.tail)
     }
}

Max function

def max(xs: List[Int]): Int = {
     if (xs.isEmpty) {
          throw new NoSuchElementException
     } else {
          if (xs.tail.isEmpty) {
               return xs.head
          }
          val tailMax = max(xs.tail)
          if (xs.head > tailMax) {
               xs.head
          } else {
               tailMax
          }
     }
}

After that, I searched for the correct answer on the web. However, I remembered that Scala offers pattern matching through something called match expressions. Therefore, it is better to say it is like advanced switch statements, a feature lacking in older versions of Java.

Sum function

def sum(xs: List[Int]): Int = xs match {
     case List() => 0
     case _ => xs.head + sum(xs.tail)
}

Max function

def max(xs: List[Int]): Int = xs match {
     case List() => throw new java.util.NoSuchElementException
     case x :: Nil => x
     case _ => val tailMax: Int = max(xs.tail);
          if (tailMax > xs.head) tailMax else xs.head
}

If you look better at the improved version with pattern matching, you can recognize that they are just better if statements.

This entry was posted in Language basics and tagged , , , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.