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

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

    You could use pattern matching like that

    def max(xs: List[Int]): Int = xs match {
      case Nil => throw new NoSuchElementException("The list is empty")
      case x :: Nil => x
      case x :: tail => x.max(max(tail)) //x.max is Integer's class method
    }
    

提交回复
热议问题