How to find the largest element in a list of integers recursively?

前端 未结 16 1846
不知归路
不知归路 2021-01-31 19:49

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

16条回答
  •  萌比男神i
    2021-01-31 20:33

    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)

提交回复
热议问题