No announcement yet.

What is the currying function

  • Filter
  • Time
  • Show
Clear All
new posts

  • What is the currying function

    What is the currying function

  • #2

    Currying is the process of taking a function with multiple arguments and turning it into a sequence of functions each with only a single argument. Currying is named after a mathematician Haskell Curry. By applying currying, a n-ary function turns it into a unary function.

    const multiArgFunction = (a, b, c) => a + b + c;
    console.log(multiArgFunction(1,2,3));// 6
    const curryUnaryFunction = a => b => c => a + b + c;
    curryUnaryFunction (1); // returns a function: b => c => 1 + b + c
    curryUnaryFunction (1) (2); // returns a function: c => 3 + c
    curryUnaryFunction (1) (2) (3); // returns the number 6

    Curried functions are great to improve code reusability and functional composition.


    • #3
      Currying may be useful if you have a function that you are passing around as a first-class object, and you don't receive all of the parameters needed to evaluate it in one place in the code. You can simply apply one or more parameters when you get them and pass the result to another piece of code that has more parameters and finish evaluating it there.

      The code to accomplish this is going to be simpler than if you need to get all the parameters together first.

      Also, there is the possibility of more code reuse, since functions taking a single parameter (another curried function) don't have to match as specifically with all the parameters.

      The practical answer is that currying makes creating anonymous functions much easier. Even with a minimal lambda syntax, it's something of a win; compare:

      map (add 1) [1..10] map (\ x -> add 1 x) [1..10]

      If you have an ugly lambda syntax, it's even worse. (I'm looking at you, JavaScript, Scheme, and Python.)


      Related Topics