The understanding of the physicalization of functions

Function currying is the technique of turning a function that takes multiple arguments into a function that takes a single argument (the first argument of the original function) and returns a new function that takes the remaining arguments and returns a result.

As an example, we have a primitive function:

function add(a, b, c) {
  return a + b + c;
}

We can convert it into a function that accepts a single parameter by currying:

function add(a) {
  return function (b) {
    return function (c) {
      return a + b + c;
    };
  };
}

In this way, we can call the new function in the following two ways:

add(1)(2)(3); // 6
add(1, 2)(3); // 6

 The main function of this technology is to make functions more flexible, more convenient to compound and combine, and to dynamically generate new functions to meet different needs. For example, we can use currying to generate some commonly used functions, such as:

const add1 = add(1);
const add2 = add(2);

add1(2)(3); // 6
add2(3)(4); // 9

In this way, we can reuse the existing curried function without redefining it every time. In addition, currying can also be used to implement the functions of some higher-order functions, such as partial application of functions, combination of functions, etc. 

Guess you like

Origin blog.csdn.net/congxue666/article/details/130562911