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

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

    If you are required to write a recursive max function on a list using isEmpty, head and tail and throw exception for empty list:

    def max(xs: List[Int]): Int =
      if (xs.isEmpty) throw new NoSuchElementException("max of empty list")
      else if (xs.tail.isEmpty) xs.head
      else if (xs.head > xs.tail.head) max(xs.head :: xs.tail.tail)
      else max(xs.tail)
    

    if you were to use max function on list it is simply (you don't need to write your own recursive function):

    val maxInt = List(1, 2, 3, 4).max
    

提交回复
热议问题