I was reading this blog post and i was not able to understand a part of the code.
object O {
def maximum(x: List[Int]): Int = x match {
case Nil => error("maximum undefined for empty list")
case x :: y :: ys => maximum((if(x > y) x else y) :: ys)
case x :: _ => x
}
}
Please explain the code maximum((if(x > y) x else y) :: ys)
How the if condition can be a part of the method maximum ?
I understand that if condition is not exactly a parameter.
In Scala,
ifis an expression, not a statement.Try this in the REPL:
ifevaluates to 1 and 1 is assigned to test. In Javaifcould be expressed with the conditional operator(x > y) ? x : yNow, you have a function called
maximumthat takes aList[Int]as a parameter.maximum((if(x > y) x else y) :: ys)calls maximum (recursively) with a list obtained prepending one betweenxandy(depending on what the if evaluates to) toys.