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

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

    The easiest approach would be to use max function of TraversableOnce trait, as follows,

    val list = (1 to 10).toList
    list.max
    

    to guard against the emptiness you can do something like this,

    if(list.empty) None else Some(list.max)
    

    Above will give you an Option[Int]

    My second approach would be using foldLeft

    (list foldLeft None)((o, i) => o.fold(Some(i))(j => Some(Math.max(i, j))))
    

    or if you know a default value to be returned in case of empty list, this will become more simpler.

    val default = 0
    (list foldLeft default)(Math.max)
    

    Anyway since your requirement is to do it in recursive manner, I propose following,

    def recur(list:List[Int], i:Option[Int] = None):Option[Int] = list match {
      case Nil => i
      case x :: xs => recur(xs, i.fold(Some(x))(j => Some(Math.max(j, x))))
    }
    

    or as default case,

    val default = 0
    def recur(list:List[Int], i:Int = default):Int = list match {
      case Nil => i
      case x :: xs => recur(xs, i.fold(x)(j => Math.max(j, x)))
    }
    

    Note that, this is tail recursive. Therefore stack is also saved.

提交回复
热议问题