Javascript currying Function

Source: Internet
Author: User
Tags javascript currying

Curring combines the concepts of functional programming with default parameters and variable parameters. A function with n parameters solidified by curried's first parameter is a fixed parameter, and returns another function object with n-1 parameters, which is similar to the behavior of the car And cdr functions of LISP, respectively. Currying can be generalized to partial function application (PFA). A function like p converts any number of (sequential) parameter functions into another function object with residual parameters.

The earliest curry function is a little polymorphism, that is, the Branch is selected internally Based on the function parameters:

//http://www.openlaszlo.org/pipermail/laszlo-user/2005-March/000350.html// ★★On 8 Mar 2005, at 00:06, Steve Albin wrote:      function add(a, b) {        if (arguments.length < 1) {          return add;        } else if (arguments.length < 2) {          return function(c) { return a + c }        } else {          return a + b;        }      }      var myadd = add( 2 );      var total = myadd(3);

A pioneer in Japan may use a very complex Regular Expression and eval to create a function closer to the meaning of modern currying when the native method of Array can be used to convert arguments to an Array.

      function curry(fun) {        if (typeof fun != 'function') {          throw new Error("The argument must be a function.");        }        if (fun.arity == 0) {          throw new Error("The function must have more than one argument.");        }        var funText = fun.toString();        var args = /function .*\((.*)\)(.*)/.exec(funText)[1].split(', ');        var firstArg = args.shift();        var restArgs = args.join(', ');        var body = funText.replace(/function .*\(.*\) /, "");        var curriedText =          "function (" + firstArg + ") {" +          "return function (" + restArgs + ")" + body +          "}";        eval("var curried =" + curriedText);        return curried;      }

<Br/> function curry (fun) {<br/> if (typeof fun! = 'Function') {<br/> throw new Error ("The argument must be a function. "); <br/>}< br/> if (fun. arity = 0) {<br/> throw new Error ("The function must have more than one argument. "); <br/>}</p> <p> var funText = fun. toString (); <br/> var args =/function. *\((. *)\)(. *)/. exec (funText) [1]. split (','); <br/> var firstArg = args. shift (); <br/> var restArgs = args. join (','); <br/> var body = funText. replace (/function. *\(. * \)/, ""); </p> <p> var curriedText = <br/> "function (" + firstArg + ") {"+ <br/>" return function ("+ restArgs +") "+ body + <br/> "}"; </p> <p> eval ("var curried =" + curriedText); <br/> return curried; <br/>}</p> <p> function sum (x, y) {<br/> return x + y; <br/>}< br/> function mean3 (a, B, c) {<br/> return (a + B + c)/3; <br/>}</p> <p> var a = curry (sum) (10) (15) <br/> alert () // 25 <br/> var B = curry (mean3) (10) (20, 30); <br/> alert (B) // 20 <br/> var c = curry (sum) (10) (20); <br/> alert (c ); <br/> var d = curry (mean3) (10) (20) (30); <br/> alert (d); <br/>

Run code

Next comes the popularity of closures. With the discovery of array-converted arguments technology, the modern currying function has finally appeared, just like 15 ~ The geographic discoveries in the age of the 17th century have suddenly broadened the world of javascript.

// A simple modern currying function curry (fn, scope) {var scope = scope | window; var args = []; for (var I = 2, len = arguments. length; I

Generally, the currying function only has two duplicates. The execution is as follows. If the first execution parameter is insufficient, the internal function is returned, and the second execution is complete. However, we can make some articles about this parameter. See the following functions:

function sum(){    var result=0;    for(var i=0, n=arguments.length; i<n; i++){        result += arguments[i];    }    return result;}alert(sum(1,2,3,4,5)); // 15

There is no such problem as parameter insufficiency. If a parameter is input, it is also calculated. But what about not passing in parameters? No error. The difference is that there are no parameters. We can keep it running, if the parameter exists. Finally, if there is no parameter, It will be executed once. In other words, the preceding steps are used to store parameters.

var sum2= curry(sum);    sum2= sum2(1)(2)(3)(4)(5);sum2(); // 15

This is a little more difficult than the general currying function. For more information, see annotations:

Var curry = function (fn) {// the parameter of the original function is the return function (args) {// the parameter of the internal function is an array, because it is executed immediately, therefore, directly to the third deduplication // args is relative to the third internal function, but the global variable var self = arguments. callee; // save itself (that is, the second function of the array as the parameter) return function () {// This is the second function called if (arguments. length) {// if there are other parameters to be added []. push. apply (args, arguments); // apply put all the currently passed parameters into args return self (args);} else {return fn. apply (this, args); // The second parameter of apply is array }}( []);};

<Br/> function sum () {<br/> var result = 0; <br/> for (var I = 0, n = arguments. length; I <n I result arguments return var curry = "function (fn) {// the parameter of the original function is function" function self = "arguments. callee; // save it as "if else fn. apply sum2 = "curry (sum ); "alert> <p> <button type =" button "title =" runcode1 "class =" runcode direct "> run the Code </button> </p> <p> or multiple parameters are input: </p> <textarea id = "runcode2" style = "width: 80%" rows = "10"> <br/> funct Ion sum () {<br/> var result = 0; <br/> for (var I = 0, n = arguments. length; I <n I result arguments return var curry = "function (fn) {// the parameter of the original function is function" function self = "arguments. callee; // save it as "if else fn. apply sum2 = "curry (sum ); "alert> <p> <button type =" button "title =" runcode2 "class =" runcode direct "> run the Code </button> </p> <p> but above functions, finally, we need to put a bracket. We want to return the result as long as the parameter is sufficient, and ignore the extra parameters. Improvements: </p> <pre class = "brush: javascript; gutter: false; toolbar: false"> function curry (f) {if (f. length = 0) return f; function iterate (args) {if (args. length <= f. length) return f. apply (null, args); return function () {return iterate (args. concat (Array. prototype. slice. call (arguments) ;};} return iterate ([]) ;}</pre> <p> <textarea id = "runcode3" style = "width: 80% "rows =" 10 "> <br/> function curry (f) {<br/> if (f. length = 0) return f; <br/> function iterate (args) {<br/> if (args. length> = f. length) <br/> return f. apply (null, args); <br/> return function () {<br/> return iterate (args. concat (Array. prototype. slice. call (arguments); <br/>}; <br/>}< br/> return iterate ([]); <br/>}< br/> function mean3 (a, B, c) {return (a + B + c)/3 ;} </p> <p> var curriedMean3 = curry (mean3); <br/> alert (curriedMean3 (1) (2, 3 )); // => 2 <br/> alert (curriedMean3 (1) (2) (3); // invalid empty parentheses <br/> alert (curriedMean3 () (1) () (2) (3); // => 2 <br/> alert (curriedMean3 (1, 2) (3, 4 )); // => 2 (the fourth parameter is invalid) <br/>

Run code

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.