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

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

    I used just head() and tail()

    def max(xs: List[Int]): Int = {
        if (xs.isEmpty) throw new NoSuchElementException
        else maxRecursive(xs.tail, xs.head) 
      }
      
      def maxRecursive(xs: List[Int], largest: Int): Int = {
        if (!xs.isEmpty) {
          if (xs.head > largest) maxRecursive(xs.tail, xs.head)
          else maxRecursive(xs.tail, largest)
        } else {
          largest
        }
      }
    

    Here is tests for this logic:

    test("max of a few numbers") {
        assert(max(List(3, 7, 2, 1, 10)) === 10)
        assert(max(List(3, -7, 2, -1, -10)) === 3)
        assert(max(List(-3, -7, -2, -5, -10)) === -2)
      }
    

提交回复
热议问题