I\'m trying to write a function which will recursively find the largest element in a list of integers. I know how to do this in Java, but can\'t understand how to do this at Sca
If you want functional approach to this problem then use reduceLeft
:
def max(xs: List[Int]) = {
if (xs.isEmpty) throw new NoSuchElementException
xs.reduceLeft((x, y) => if (x > y) x else y)
}
This function specific for list of ints, if you need more general approach then use Ordering
typeclass:
def max[A](xs: List[A])(implicit cmp: Ordering[A]): A = {
if (xs.isEmpty) throw new NoSuchElementException
xs.reduceLeft((x, y) => if (cmp.gteq(x, y)) x else y)
}
reduceLeft
is a higher-order function, which takes a function of type (A, A) => A
, it this case it takes two ints, compares them and returns the bigger one.