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

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

    I presume this is for the progfun-example

    This is the simplest recursive solution I could come up with

      def max(xs: List[Int]): Int = {
        if (xs.isEmpty) throw new NoSuchElementException("The list is empty")
        val tail = xs.tail
        if (!tail.isEmpty) maxOfTwo(xs.head, max(xs.tail))
        else xs.head
      }
    
      def maxOfTwo(x: Int, y: Int): Int = {
        if (x >= y) x
        else y
      }
    

提交回复
热议问题