Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Partially applied functions with all arguments missing in Scala

From my understanding, a partially applied function are functions, which we can invoke without passing all/some of the required arguments.

def add(x:Int, y:Int) = x + y
val paf = add(_ :Int, 3)
val paf1 = add(_ :Int, _ :Int)

In the above example, paf1 refers to partially applied function with all the arguments missing and I can invoke is using: paf1(10,20) and the original function can be invoked using add(10,20)

My question is, what is the extra benefit of creating a partially applied function with all the arguments missing, since the invocation syntax is pretty much the same? Is it just to convert methods into first class functions?

like image 756
Chander Shivdasani Avatar asked Dec 21 '22 04:12

Chander Shivdasani


1 Answers

Scala's def keyword is how you define methods and methods are not functions (in Scala). So your add is not a first-class function entity the way your paf1 is, even if they're semantically equivalent in what they do with their arguments in producing a result.

Scala will automatically use partial application to turn a method into an equivalent function, which you can see by extending your example a bit:

def add(x: Int, y: Int) = x + y
...
val pa2: (Int, Int) => Int = add
pa2: (Int, Int) => Int = <function2>

This may seem of little benefit in this example, but in many cases there are non-explicit constraints indicating a function is required (or more accurately, constraints specified explicitly elsewhere) that allow you to simply give a (type-compatible) method name in a place where you need a function.

like image 183
Randall Schulz Avatar answered Apr 26 '23 22:04

Randall Schulz