2017-12-02 302 views
0

在使用Scala进行函数式编程的过程中,我看到了两种形式的def声明。但我不知道它们之间的差异,也不知道它的名称。我如何获得更多关于此的信息?高级函数

宣言1

def sum(f: Int => Int)(a: Int, b: Int): Int = ???

宣言2

def sum(f: Int => Int, a: Int, b: Int): Int = ???

回答

2

第一个被称为咖喱语法。

您可以部分应用该功能,然后返回一个新功能。

scala> def sum(f: Int => Int)(a: Int, b: Int): Int = f(a) + f(b) 
sum: (f: Int => Int)(a: Int, b: Int)Int 

scala> sum({x: Int => x + 1}) _ 
res10: (Int, Int) => Int = $$Lambda$1115/1[email protected]21de 

第二个是uncurried语法,但即使在这种情况下,我们仍然可以部分地应用该函数。

scala> def sum(f: Int => Int, a: Int, b: Int): Int = f(a) + f(b) 
sum: (f: Int => Int, a: Int, b: Int)Int 

scala> sum({x: Int => x + 1}, _: Int, _: Int) 
res11: (Int, Int) => Int = $$Lambda$1116/[email protected] 

再次部分应用时返回新函数。

上面两个声明没有区别,它只是语法糖。