<!DOCTYPE html> <html lang="zh-cn"> <head> <meta charset="UTF-8"> <title>JS 柯里化(Currying)</title> </head> <body> <script type="text/javascript"> //f(x) and g(x) are synthesized into f(g(x)), there is a hidden premise that both f and g can only accept one parameter. //If you can accept multiple parameters, such as f(x, y) and g(a, b, c), function composition is very troublesome. //At this time, function currying is required. The so-called "currying" is to convert a multi-parameter function into a single-parameter function. //Explanation of group friends (Xiaoshuo) //Currying is to turn a function with n parameters into n functions with only 1 parameter //Explanation of group friends (Cloud) //Currying generally uses closures, because you need to access the variables returned in the previous function after the last call //Explanation of group friends (carved brother) //Currying is to turn a multi-argument function into a function that takes only one argument at a time //before currying function add(x,y){ return x+y; } console.info('Before currying: '+add(4,5)); //After currying, this is also currying + closure function add2(x){ return function(y){ return x+y; }; } console.info('After currying: '+add2(4)(5)); // Deeper currying, this is also currying + closure function add3(x){ var sum = x; var tmp = function(y){ sum = sum + y; return tmp; }; tmp.toString = function(){ return sum; }; return tmp; } console.info('Deeper currying: '+add3(4)(5)(6)(7)(8)(9)); //equal to add3 = add3f function add3f(x){ return function(y){ return function(z){ return function(a){ return function(b){ return function(c){ return x+y+z+a+b+c; }; }; }; }; }; } console.info('add3 = add3f:'+add3f(4)(5)(6)(7)(8)(9)); //function declaration and function expression (fe) //function declaration: function fn(){}; //Function expression: var aaa = function fn(){}; var aaa = function(){}; //Let's talk about assigning an anonymous function to a variable //Currying of function expressions, this is also currying + closure var add4 = function(x){ var sum = x; var tmp = function(y){ sum = sum + y; return tmp; }; tmp.toString = function(){ return sum; }; return tmp; } console.info('Currying of function expressions: '+add4(4)(5)(6)(7)(8)); </script> </body> </html>
PS: The extension of group friends (carved brothers)
The origin of currying should be λ calculus
. There is only one data type in λ calculus, function. This function only accepts one parameter and returns only one parameter,
and this parameter is also a single-valued function.
Effect picture: