scala currying by nested functions or by multiple parameter lists

后端 未结 3 1637
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-30 14:21

In Scala, I can define a function with two parameter lists.

def myAdd(x :Int)(y :Int) = x + y

This makes it easy to define a partially appl

3条回答
  •  死守一世寂寞
    2020-12-30 15:02

    You could also do this:

    def yetAnotherAdd(x: Int) = x + (_: Int)
    

    You should choose the API based on intention. The main reason in Scala to have multiple parameter lists is to help type inference. For instance:

    def f[A](x: A)(f: A => A) = ...
    f(5)(_ + 5)
    

    One can also use it to have multiple varargs, but I have never seen code like that. And, of course, there's the need for the implicit parameter list, but that's pretty much another matter.

    Now, there are many ways you can have functions returning functions, which is pretty much what currying does. You should use them if the API should be thought of as a function which returns a function.

    I think it is difficult to get any more precise than this.

提交回复
热议问题