开发者

Difference between similar curried types in Scala

What is the difference between the types of the following two functions?

def add1: Int => Int => Int = a => b => a + b
def add2(a: Int)(b: Int) = a + b

Based on their declarations, they seem to have the same type. Both are called in the same way:

scala> add1(1)(2)
res2: Int = 3

scala> add2(1)(2)
res3: Int = 3

However, there is an apparent difference in their types:

scala> :t add1
Int => Int => Int

scala> :t add2
(a: Int)(b: Int)Int

Additionally, partial application of add1 is a bit cleaner than of add2.

scala> add1(1)
res4: Int => Int = <function1>

scala> add2(1)(_)
res5: Int => Int开发者_运维问答 = <function1>


add1 is a method with no parameters that returns a Function1[Int, Function1[Int, Int]]. add2 is a method that takes two parameter lists and returns an Int.

Further reading:

Difference between method and function in Scala


x.add1 is a function Int => Int => Int.

x.add2 is a method, which is not a value and doesn't have the same type as add1. To get an object equivalent to x.add1, you have to use x.add2 _.


There certainly is a difference between the two definitions. Consider passing each a single argument.

add1(1)
(Int) => Int = <function1>

add2(1)
<console>:9: error: missing arguments for method add2 in object $iw;
follow this method with `_' if you want to treat it as a partially applied function
       add2(1)

However, if you partially apply add2 it has the same type as add1.

scala> :t add1
(Int) => (Int) => Int

scala> :t add2 _
(Int) => (Int) => Int

I understand add1 perfectly well. It's an anonymous function that takes an Int and returns and Int=>Int. This is the classic definition of a curried function.

I need to do more reading before I understand add2 perfectly well. As far as I can tell, it's a method of writing functions that take their parameters in a different form (i.e. add2(1)(2)) and can easily be transformed into a curried function (add2 _).

Hope this helps! I also look forward to a better explanation about add2.

Edit: this is a great document about curried methods in scala: http://www.codecommit.com/blog/scala/function-currying-in-scala

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜