Simple Scala methods for sum and maximum

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

There are at least 2 different ways how to solve each function. First I tried to just come up with a recursive approach at all 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 right answer on the web. However, I remembered that Scala offers pattern matching trough something what is called in Scala match expressions. It is better to say advanced switch statements which are 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 on the improved version with pattern matching, you can recognize that they are just better if statements.

This entry was posted in Scala 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.