Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala partial application unclear

I don't have very clear the partial application of functions in Scala... I will do an example:

def myOperation(x: Int)(y: Int): Int = {
    val complexVal = complexCalc(x)
    println("complexVal calculated")
    complexVal + y
}
def complexCalc(x: Int): Int = x * 2

val partial = myOperation(5)_

println("calculate")
println("result(3): " + partial(3))
println("result(1): " + partial(1))

The output of this will be:

calculate
complexVal calculated
result(3): 13
complexVal calculated
result(1): 11

So the complexVal was calculated 2 times, what if I want to calculate it just once?

For who has javascript knowledge something like:

function myOperation(x) {
     var complexVal = complexCalc(x)
     return function(y){
         complexVal + y
     }
}

EDIT:
So what's the difference between what I've written previously and this:

def myOperation2(x: Int, y: Int): Int = {
    val complexVal = complexCalculation(x)
    println("complexVal calculated")
    complexVal + y
}

val partial = myOperation(5)_
val partial2 = myOperation2(5, _: Int)
like image 535
rascio Avatar asked May 26 '14 14:05

rascio


2 Answers

You can explicitly return a function from myOperation:

def myOperation(x: Int): Int => Int = {
    val complexVal = complexCalc(x)
    println("complexVal calculated")
    (y: Int) => complexVal + y
}
like image 58
Lee Avatar answered Nov 22 '22 07:11

Lee


Partial application just creates a new function by filling in some of the arguments of an existing function, but does not actually execute any part of that function.

For what you're trying to do, you want to return a function from a function. In this case, what you're actually doing is currying (true currying).

Try this:

def myOperation(x : Int) : (Int => Int => Int) = {
   val complexVal = complexCalc(x)
   (y : Int) => complexVal + y
}
like image 41
reggert Avatar answered Nov 22 '22 07:11

reggert