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

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

    1. Folding can help:

      if(xs.isEmpty)
        throw new NoSuchElementException
      else
        (Int.MinValue /: xs)((max, value) => math.max(max, value))
      
    2. List and pattern matching (updated, thanks to @x3ro)

      def max(xs:List[Int], defaultValue: =>Int):Int = {
        @tailrec
        def max0(xs:List[Int], maxSoFar:Int):Int = xs match {
          case Nil => maxSoFar
          case head::tail => max0(tail, math.max(maxSoFar, head))
        }
        if(xs.isEmpty)
          defaultValue
        else
          max0(xs, Int.MinValue)
      }
      

    (This solution does not create Option instance every time. Also it is tail-recursive and will be as fast as an imperative solution.)

提交回复
热议问题