何时使用部分应用功能 [英] When to use Partially Applied Functions

查看:106
本文介绍了何时使用部分应用功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

注意:如果您只是想跳过上下文,请跳到下面的问题。



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

这个例子确实有帮助,但是我很难解释一个通用的这是你什么时候使用部分应用函数的时候。



问题:任何人都有自己的方式来成功地解释部分应用函数,它真的为Java(或其他面向对象语言)开发人员带来家庭感受?

$ b $

       def withTax(cost:Float,state:String)= {/ *一些复杂的查找表* /} 

现在假设你想制作一个埠

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

您可以从原始方法中重用最大的代码,通过不必指定(本地)始终相同的参数,重复性任务的最大便利性。



人们经常试图用implicits来解决这个问题:

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

不要这样做! (并非没有仔细考虑。)很难跟踪当时哪个隐含val发生。使用部分应用功能,您可以节省相同的打字费用,并且您知道您正在使用哪一种功能,因为您每次使用时都键入该名称!


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!

这篇关于何时使用部分应用功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆