Hey there! Welcome to ClearUrDoubt.com. In this post, we will look at a Scala program to find the largest number in a given list of integers. Let’s look at the program:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
|
package com.clearurdoubt.practice object FindMax extends App { def max(xs: List[Int]): Int = { @annotation.tailrec def max(xs: List[Int], maximum: Int) : Int = xs match { case Nil => throw new java.util.NoSuchElementException("Empty List") case x :: Nil => if(x > maximum) x else maximum case x :: y :: xs1 => if (x >= y) max(xs1, x) else max(xs1, y) } max(xs, Int.MinValue) } println("Max of List(1,-5,10,3,9) is : " + max(List(1,-5,10,3,9))) } |
Output: Happy learning. Please leave a reply in Read more