What is 'Currying'?

前端 未结 18 1610
遥遥无期
遥遥无期 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:27

    Currying is a transformation that can be applied to functions to allow them to take one less argument than previously.

    For example, in F# you can define a function thus:-

    let f x y z = x + y + z
    

    Here function f takes parameters x, y and z and sums them together so:-

    f 1 2 3
    

    Returns 6.

    From our definition we can can therefore define the curry function for f:-

    let curry f = fun x -> f x
    

    Where 'fun x -> f x' is a lambda function equivilent to x => f(x) in C#. This function inputs the function you wish to curry and returns a function which takes a single argument and returns the specified function with the first argument set to the input argument.

    Using our previous example we can obtain a curry of f thus:-

    let curryf = curry f
    

    We can then do the following:-

    let f1 = curryf 1
    

    Which provides us with a function f1 which is equivilent to f1 y z = 1 + y + z. This means we can do the following:-

    f1 2 3
    

    Which returns 6.

    This process is often confused with 'partial function application' which can be defined thus:-

    let papply f x = f x
    

    Though we can extend it to more than one parameter, i.e.:-

    let papply2 f x y = f x y
    let papply3 f x y z = f x y z
    etc.
    

    A partial application will take the function and parameter(s) and return a function that requires one or more less parameters, and as the previous two examples show is implemented directly in the standard F# function definition so we could achieve the previous result thus:-

    let f1 = f 1
    f1 2 3
    

    Which will return a result of 6.

    In conclusion:-

    The difference between currying and partial function application is that:-

    Currying takes a function and provides a new function accepting a single argument, and returning the specified function with its first argument set to that argument. This allows us to represent functions with multiple parameters as a series of single argument functions. Example:-

    let f x y z = x + y + z
    let curryf = curry f
    let f1 = curryf 1
    let f2 = curryf 2
    f1 2 3
    6
    f2 1 3
    6
    

    Partial function application is more direct - it takes a function and one or more arguments and returns a function with the first n arguments set to the n arguments specified. Example:-

    let f x y z = x + y + z
    let f1 = f 1
    let f2 = f 2
    f1 2 3
    6
    f2 1 3
    6
    

提交回复
热议问题