Different brackets style on Scala function definition parameter list

 ̄綄美尐妖づ 提交于 2019-12-07 03:26:43

问题


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


回答1:


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 Ints 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.




回答2:


Scala functions support multiple parameter lists to aid in currying. From your first example, you can view the first sum function as one that takes two integers and returns another function (i.e. curries) which can then take an Int => Int function as an argument.

This syntax is also used to create functions that look and behave as new syntax. For example, def withResource(r: Resource)(block: => Unit) can be called:

withResource(res) { 
    ..
    ..
}


来源:https://stackoverflow.com/questions/19036682/different-brackets-style-on-scala-function-definition-parameter-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!