Why can't i rewrite
println(abc.foldRight(0)((a,b) => math.max(a.length,b)))
in
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,_)))
? scala
interpreter yields
/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 descriptive enough for me. Isn't resulting lambda takes two parameters one of which being called for .length method, as in abc.map(_.length)
?
The Partially applied functions are the functions which are not applied on all the arguments defined by the stated function i.e, while invoking a function, we can supply some of the arguments and the left arguments are supplied when required.
Simple answer. Currying: Lets you call a function, splitting it in multiple calls, providing one argument per-call. Partial Application: Lets you call a function, splitting it in multiple calls, providing multiple arguments per-call.
Currying is the process of converting a function with multiple arguments into a sequence of functions that take one argument. Each function returns another function that consumes the following argument.
=> is syntactic sugar for creating instances of functions. Recall that every function in scala is an instance of a class. For example, the type Int => String , is equivalent to the type Function1[Int,String] i.e. a function that takes an argument of type Int and returns a String .
abc.foldRight(0)(math.max(_.length, _))
will expand to something like abc.foldRight(0)(y => math.max(x => x.length, y))
. The placeholder syntax expands in the nearest pair of closing parentheses, except when you have only the underscore in which case it will expand outside the closest pair of parentheses.
You can use abc.foldRight(0)(_.length max _)
which doesn't suffer from this drawback.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With