Scala中缺少所有参数的部分应用函数 [英] Partially applied functions with all arguments missing in Scala
问题描述
的情况下调用所有/必需的参数。
def add(x:Int,y:Int)= x + y
val paf = add(_: Int,3)
val paf1 = add(_:Int,_:Int)
在上面的例子中,paf1引用了部分应用的函数,所有参数都丢失了,我可以使用: paf1(10,20)
,并且可以调用原始函数 add(10,20)
我的问题是,创建部分应用函数的额外好处是什么所有的参数缺失,因为调用语法几乎相同?只是将方法转换为一流的功能?
def
关键字是您如何定义方法和方法不是函数(在Scala中)。因此,即使你的 paf1
是语义上等价的,你的 add 不是一个一流的函数实体在他们用它们的参数来处理结果的过程中。
Scala会自动使用部分应用程序将一个方法转换为等效函数,您可以通过扩展您的示例有点:
def add(x:Int,y:Int)= x + y
...
val pa2:(Int,Int)=> Int = add
pa2:(Int,Int)=> Int =< function2>
这个例子看起来没什么好处,但在很多情况下,有非显式约束指示一个函数是必需的(或者更准确地说,在其他地方明确指定的约束),它允许您在需要函数的地方给出(类型兼容的)方法名称。
From my understanding, a partially applied function are functions, which we can invoke without
passing all/some of the required arguments.
def add(x:Int, y:Int) = x + y
val paf = add(_ :Int, 3)
val paf1 = add(_ :Int, _ :Int)
In the above example, paf1 refers to partially applied function with all the arguments missing and I can invoke is using: paf1(10,20)
and the original function can be invoked using add(10,20)
My question is, what is the extra benefit of creating a partially applied function with all the arguments missing, since the invocation syntax is pretty much the same? Is it just to convert methods into first class functions?
解决方案 Scala's def
keyword is how you define methods and methods are not functions (in Scala). So your add
is not a first-class function entity the way your paf1
is, even if they're semantically equivalent in what they do with their arguments in producing a result.
Scala will automatically use partial application to turn a method into an equivalent function, which you can see by extending your example a bit:
def add(x: Int, y: Int) = x + y
...
val pa2: (Int, Int) => Int = add
pa2: (Int, Int) => Int = <function2>
This may seem of little benefit in this example, but in many cases there are non-explicit constraints indicating a function is required (or more accurately, constraints specified explicitly elsewhere) that allow you to simply give a (type-compatible) method name in a place where you need a function.
这篇关于Scala中缺少所有参数的部分应用函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!