开发者

When to use Partially Applied Functions [closed]

开发者 https://www.devze.com 2023-03-29 02:58 出处:网络
Closed. This question is opinion-based. It is not currently accepting answers. Want to improve this question? Update the question so it can be answered with facts and citations by editing th
Closed. This question is opinion-based. It is not currently accepting answers.

Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.

Closed 8 years ago.

Improve this question

Note: jump down to "Question" below if you just want to skip the context

When giving talks on Scala I pretty much give "toy problems" like the one below as examples of Partially Applied Functions.

def multiply(x:Int, y:Int): Int = x * y
val x5 = multiply(5, _:Int)
x5(10) //produces 50

This example does help, however it's tough for me to explain a general "this is when you'd recognize when to use a partially applied function".

Question: Anyone have their own way of开发者_开发技巧 successfully explaining Partially Applied Functions that really hits home for Java (or other OO language) developers?


Suppose you want to apply sales tax.

def withTax(cost: Float, state: String) = { /* Some complicated lookup table */ }

Now suppose you want to make a bunch of purchases in New York.

val locallyTaxed = withTax(_: Float, "NY")
val costOfApples = locallyTaxed(price("apples"))

You get maximal code reuse from the original method, yet maximal convenience for repetitive tasks by not having to specify the parameters that are (locally) always the same.

People often try to solve this with implicits instead:

def withTax(cost: Float)(implicit val state: String) = ...

Don't do it! (Not without careful consideration.) It's hard to keep track of which implicit val happens to be around at the time. With partially applied functions, you get the same savings of typing, plus you know which one you're using because you type the name every time you use it!


In Java you often pass in the first (or more) arguments of a partially applied function to the constructor of a class. Rex's example might then look something like this:

class TaxProvider {
    final String state;

    TaxProvider(String state) {
        this.state = state;
    }

    double getTaxedCost(double cost) {
      return ... // look up tax for state and apply to cost
    }
}


TaxProvider locallyTaxed = new TaxProvider("NY")
double costOfApples = locallyTaxed.getTaxedCost(price("apples"))


I guess Scala has function composition, this is something where partially applied functions shine.

Another point are higher order functions like filter that take a predicate, and their usage like in:

filter (<42) list  -- sorry, don't speak Scala

The predicate is often some partially applied function. Same holds for map, fold etc.

0

精彩评论

暂无评论...
验证码 换一张
取 消