Scala函数定义参数列表中的不同括号样式 [英] Different brackets style on Scala function definition parameter list
问题描述
Scala中以下两个函数定义的区别:
$ b <1> def sum(f:Int => Int) (a:Int,b:Int):Int = {<代码移除> }
<2>
def sum(f:Int => Int,a:Int,b:Int) :Int = {<代码移除> }
?
SBT的控制台REPL为它们提供了不同的值,他们是不同的: 例如,如果您知道您想在当前方法中使用的函数,但尚未知道参数,则可以这样使用它: 此时,
$ b $ p sum:(f:Int => Int,a:Int,b:Int)Int $ c $:
s并返回一个
$ b sum:(f:Int => Int)(a:Int,b:Int)Int $ c $第一个定义是 您可以在另一次提供
a
和 b
。
def mySum(v:Int):Int = v + 1
val newsum = sum(mySum)_
newsum
是一个函数, code> Int Int
。
在上下文中总结它似乎没有太大意义;然而,我曾经有很多次想要根据我现在知道的东西返回不同的算法部分程序,但不知道(或有权访问)参数。
Currying会为您购买该功能。
What is the difference of the following two function definitions in Scala:
1) def sum(f: Int => Int)(a: Int, b: Int): Int = { <code removed> }
2) def sum(f: Int => Int, a: Int, b: Int): Int = { <code removed> }
?
SBT's console REPL gives different value for them so looks if they are somehow different:
sum: (f: Int => Int, a: Int, b: Int)Int
sum: (f: Int => Int)(a: Int, b: Int)Int
The first definition is curried, so that you can provide a
and b
at another time.
For instance, if you know the function you want to use in the current method, but don't yet know the arguments, you can use it so:
def mySum(v: Int): Int = v + 1
val newsum = sum(mySum) _
At this point, newsum
is a function that takes two Int
s and returns an Int
.
In the context of summing it doesn't seem to make much sense; however, there have been plenty of times I've wanted to return different algorithms for parts of a program based upon something I know now, but don't know (or have access to) the parameters yet.
Currying buys you that feature.
这篇关于Scala函数定义参数列表中的不同括号样式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!