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
Looks like you're just starting out with scala so I try to give you the simplest answer to your answer, how do it recursively:
def max(xs: List[Int]): Int = {
def maxrec(currentMax : Int, l: List[Int]): Int = l match {
case Nil => currentMax
case head::tail => maxrec(head.max(currentMax), tail) //get max of head and curretn max
}
maxrec(xs.head, xs)
}
This method defines an own inner method (maxrec
) to take care of the recursiveness. It will fail ( exception) it you give it an empty list ( there's no maximum on an empty List)