What is currying and how does it work?
TL;DR
Currying is a technique in functional programming where a function that takes multiple arguments is transformed into a series of functions that each take a single argument. This allows for partial application of functions. For example, a function f(a, b, c)
can be curried into f(a)(b)(c)
. Here's a simple example in JavaScript:
function add(a) {
return function (b) {
return function (c) {
return a + b + c;
};
};
}
const addOne = add(1);
const addOneAndTwo = addOne(2);
const result = addOneAndTwo(3); // result is 6
What is currying and how does it work?
Definition
Currying is a functional programming technique where a function with multiple arguments is decomposed into a sequence of functions, each taking a single argument. This allows for the partial application of functions, enabling more flexible and reusable code.
How it works
- Transformation: A function that takes multiple arguments is transformed into a series of nested functions, each taking one argument.
- Partial application: You can call the curried function with fewer arguments than it expects, and it will return a new function that takes the remaining arguments.
Example in JavaScript
Here's a simple example to illustrate currying in JavaScript:
// Non-curried function
function add(a, b, c) {
return a + b + c;
}
// Curried version of the same function
function curriedAdd(a) {
return function (b) {
return function (c) {
return a + b + c;
};
};
}
// Using the curried function
const addOne = curriedAdd(1);
const addOneAndTwo = addOne(2);
const result = addOneAndTwo(3); // result is 6
Benefits of currying
- Reusability: Curried functions can be reused with different sets of arguments.
- Partial application: You can create new functions by fixing some arguments of the original function.
- Function composition: Currying makes it easier to compose functions, leading to more readable and maintainable code.
Practical example
Consider a function that calculates the volume of a rectangular prism:
function volume(length, width, height) {
return length * width * height;
}
// Curried version
function curriedVolume(length) {
return function (width) {
return function (height) {
return length * width * height;
};
};
}
// Using the curried function
const volumeWithLength5 = curriedVolume(5);
const volumeWithLength5AndWidth4 = volumeWithLength5(4);
const result = volumeWithLength5AndWidth4(3); // result is 60
Currying with arrow functions
You can also use arrow functions to make the syntax more concise:
const curriedAdd = (a) => (b) => (c) => a + b + c;
const addOne = curriedAdd(1);
const addOneAndTwo = addOne(2);
const result = addOneAndTwo(3); // result is 6