What is 'Currying'?

前端 未结 18 1301
遥遥无期
遥遥无期 2020-11-21 05:26

I\'ve seen references to curried functions in several articles and blogs but I can\'t find a good explanation (or at least one that makes sense!)

18条回答
  •  滥情空心
    2020-11-21 06:24

    A curried function is applied to multiple argument lists, instead of just one.

    Here is a regular, non-curried function, which adds two Int parameters, x and y:

    scala> def plainOldSum(x: Int, y: Int) = x + y
    plainOldSum: (x: Int,y: Int)Int
    scala> plainOldSum(1, 2)
    res4: Int = 3
    

    Here is similar function that’s curried. Instead of one list of two Int parameters, you apply this function to two lists of one Int parameter each:

    scala> def curriedSum(x: Int)(y: Int) = x + y
    curriedSum: (x: Int)(y: Int)Intscala> second(2)
    res6: Int = 3
    scala> curriedSum(1)(2)
    res5: Int = 3
    

    What’s happening here is that when you invoke curriedSum, you actually get two traditional function invocations back to back. The first function invocation takes a single Int parameter named x , and returns a function value for the second function. This second function takes the Int parameter y.

    Here’s a function named first that does in spirit what the first traditional function invocation of curriedSum would do:

    scala> def first(x: Int) = (y: Int) => x + y
    first: (x: Int)(Int) => Int
    

    Applying 1 to the first function—in other words, invoking the first function and passing in 1 —yields the second function:

    scala> val second = first(1)
    second: (Int) => Int = 
    

    Applying 2 to the second function yields the result:

    scala> second(2)
    res6: Int = 3
    

提交回复
热议问题