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

前端 未结 16 1638
不知归路
不知归路 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:21

    With pattern matching to find max and return zero in case empty

      def findMax(list: List[Int]) = {
        def max(list: List[Int], n: Int) : Int = list match {
          case h :: t => max(t, if(h > n) h else n)
          case _ => n
        }
        max(list,0)
      }
    

提交回复
热议问题