Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala partially applied curried functions

Tags:

scala

currying

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)?

like image 410
Alexander Tumin Avatar asked Feb 24 '12 10:02

Alexander Tumin


People also ask

What is partially applied functions in Scala?

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.

What is the difference between partial application and currying?

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.

What is curried function in Scala?

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.

What is the meaning of => in Scala?

=> 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 .


1 Answers

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.

like image 178
missingfaktor Avatar answered Sep 29 '22 05:09

missingfaktor