简体   繁体   中英

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)

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
}

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
}

Partial application binds a value to a function argument to give you a function with decreased arity (ie fewer arguments). This does not provide any form of memoisation of your expensive computation.

Lee's answer is perfectly good way of solving that problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM