Scala partially applied curry functions

Why can not I rewrite

println(abc.foldRight(0)((a,b) => math.max(a.length,b)))

at

object Main {
  def main(args : Array[String]) {
    val abc = Array[String]("a","abc","erfgg","r")
    println(abc.foldRight(0)((a,b) => math.max(a.length,b)))
  }
}

to

println(abc.foldRight(0)(math.max(_.length,_)))

? scalatranslator gives

/path/to/Main.scala:4: error: wrong number of parameters; expected = 2
    println(abc.foldRight(0)(math.max(_.length,_)))
                                     ^
one error found

Which is not enough for me. It doesn’t work. Lambda accepts two parameters, one of which is called for the .length method, as in abc.map(_.length)?

+5
source share
1 answer

abc.foldRight(0)(math.max(_.length, _))will expand to a value abc.foldRight(0)(y => math.max(x => x.length, y)). Placeholder syntax expands in the closest pair of closing parentheses, unless you only have an underscore, in which case it will expand outside the nearest pair of parentheses.

You can use abc.foldRight(0)(_.length max _)one that does not suffer from this drawback.

+9
source

All Articles