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

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

    If you want functional approach to this problem then use reduceLeft:

    def max(xs: List[Int]) = {
      if (xs.isEmpty) throw new NoSuchElementException
      xs.reduceLeft((x, y) => if (x > y) x else y)
    }
    

    This function specific for list of ints, if you need more general approach then use Ordering typeclass:

    def max[A](xs: List[A])(implicit cmp: Ordering[A]): A = {
      if (xs.isEmpty) throw new NoSuchElementException
      xs.reduceLeft((x, y) => if (cmp.gteq(x, y)) x else y)
    }   
    

    reduceLeft is a higher-order function, which takes a function of type (A, A) => A, it this case it takes two ints, compares them and returns the bigger one.

提交回复
热议问题