DEV Community

Awais Akram Mughal
Awais Akram Mughal

Posted on

Currying Function and It's Advantages

  • Turning a function that takes multiple arguments, to a function which returns functions (Unary and Anonymous).

  • Currying is right-associative (Read from Right-Left).

  • The concept acts systematic: Property needs to interact with other basic properties in order to fully develop its advantages. There is a mutual dependency between the properties involved.

  • Makes working with HOC(Higher Order Component) much more effective, provided the passed in functions are in curried form themselves.

Let's Look at an Example:

// * Abstraction over Arity(the amount of functions you can curry into one function)

const comp = f => g => x => f(g(x));
const inc = x => x + 1; // * Unary Function
const mul = y => x => x * y; // * Binary Function

// * Normal Composition of two unary Functions:
comp(inc)(inc)(2); // * 4

// * Composition of Binary and Unary Funtions:
comp(mul)(inc)(2)(3); // * 9

// * Invalid Composition of an inner binary Function:
comp(inc)(mul)(2)(3); // * Type Error
Enter fullscreen mode Exit fullscreen mode

Let's look at the Invalid Composition Example:

  • Here, f's arity doesn't matter, because "comp" is polymorphic in nature/return.

  • If f is substituted with inc, comp's return type becomes:

x => f(g(x))
Enter fullscreen mode Exit fullscreen mode
  • If f is substituted with mul, comp's return type becomes:
x => y => f(g(x))(y)
Enter fullscreen mode Exit fullscreen mode

Which is perfectly valid. However, mul here is g and it requires 2 arguments but only one is given, hence, type error.

Important Things to note here:

  • Arguments Order matters, it only concerns non-commutative functions.

  • Primary parameters should be placed at the end to facilitate function composition.

  • Parameters that are least likely to change should be place leftmost to facilitate partially applied functions.

DON'T:

  • Rely on function's length property.

  • Use magic auto currying, that is, functions as return values are curried automatically.

Top comments (0)