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

前端 未结 16 1639
不知归路
不知归路 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条回答
  •  独厮守ぢ
    2021-01-31 20:30

    With tail-recursion

      @tailrec
      def findMax(x: List[Int]):Int =  x match {
        case a :: Nil => a
        case a :: b :: c =>  findMax( (if (a > b) a else b) ::c)
      }
    

提交回复
热议问题