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

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

    Scala is a functional language whereby one is encourage to think recursively. My solution as below. I recur it base on your given method.

      def max(xs: List[Int]): Int = {
        if(xs.isEmpty == true) 0
        else{
          val maxVal= max(xs.tail)
          if(maxVal >= xs.head) maxVal 
          else                  xs.head     
        }
      }
    

    Updated my solution to tail recursive thanks to suggestions.

      def max(xs: List[Int]): Int = {    
        def _max(xs: List[Int], maxNum: Int): Int = {   
          if (xs.isEmpty) maxNum
          else {
            val max = {
              if (maxNum >= xs.head) maxNum
              else xs.head
            }
            _max(xs.tail, max)
          }
        }
        _max(xs.tail, xs.head)
      }
    

提交回复
热议问题