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!
在 Java 中,您经常将部分应用函数的第一个(或多个)参数传递给类的构造函数。 Rex 的示例可能如下所示:
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"))
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"))
发布评论
评论(3)
假设您要征收销售税。
现在假设您想在纽约购买大量商品。
您可以从原始方法中获得最大程度的代码重用,同时通过不必指定(本地)始终相同的参数来为重复任务提供最大的便利。
人们经常尝试用隐式方法来解决这个问题:
不要这样做! (并非没有经过仔细考虑。)很难跟踪当时恰好存在哪个隐式 val。通过部分应用函数,您可以节省相同的键入时间,而且您知道自己正在使用哪一个函数,因为每次使用时都需要键入名称!
Suppose you want to apply sales tax.
Now suppose you want to make a bunch of purchases in New York.
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:
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!
在 Java 中,您经常将部分应用函数的第一个(或多个)参数传递给类的构造函数。 Rex 的示例可能如下所示:
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:
我猜 Scala 有函数组合,这是部分应用函数的亮点。
另一点是像
filter
这样采用谓词的高阶函数,它们的用法如下:谓词通常是一些部分应用的函数。对于
map
、fold
等也是如此。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:The predicate is often some partially applied function. Same holds for
map
,fold
etc.