JavaScript Basics Curry (021)

Source: Internet
Author: User

we want the function to take the parameters in step, and get the results when all the parameters are in place. To implement this mechanism, we first understand the application of the function in javascript:

1. "Application" of functions (function application)

In a functional programming language, a function is not called (invoked) or executed (called), but is applied (applied). In JavaScript, a function is an object, so it can also be "applied": Function.prototype.apply (). Here's an example:
Define a Functionvar Sayhi = function (WHO) {    return ' Hello ' + (who?) "," + Who: "") + "!";};/ /Invoke a functionsayhi (); "Hello" Sayhi (' World '); "Hello, world!." Apply a functionsayhi.apply (null, ["Hello"]); "Hello, hello!."
As you can see from this example, the result of invoking a function is the same as the result of applying a function. The Apply () method of the function receives two parameters, the first parameter is an object, which is bound to the this object reference inside the function declaration during the execution of the function, and the other parameter is an array that is used to pass the parameters of the function. If the first argument is null, then the function will point to the global object when it is executed: that is, the function (not including the method within the function) is executed(invoked) occurs. When a method within a function is applied (applied), the first argument cannot be passed null, and it should pass the object to which the method belongs:
var alien = {    Sayhi:function (WHO) {        return ' Hello ' + (who?) "," + Who: "") + "!";    }; Alien.sayhi (' World '); "Hello, world!." Sayhi.apply (Alien, ["humans"]); "Hello, humans!."
So in the above example, the This reference method in the method belongs to the object, and the this in the function, if not specifically given, refers to the global object. As you can see from the two examples above, the function execution in JavaScript is actually the application process of the function. In addition to the apply, the function has another similar intrinsic method called call, when the function has only one argument, the second argument of the calling can not pass an array, but gives the only argument directly:
The second is more efficient, saves an arraysayhi.apply (alien, ["humans"]); "Hello, humans!." Sayhi.call (Alien, "humans"); "Hello, humans!."
2. Partial application of functions (partial application)Since the execution of the function is the process of applying parameters to it, can we apply the parameters of the function in steps? For example, we have an add (x, y) function that does the addition calculation, is it possible to apply one parameter before applying the next (note that the following code is not legal, just as a demo):
For illustration purposes//not valid javascript//we had this functionfunction add (x, y) {    return x + y;} And we know the Argumentsadd (5, 4);//Step 1--Substitute one argumentfunction add (5, y) {    return 5 + y;} Step 2--substitute the other argumentfunction add (5, 4) {    return 5 + 4;} The Step1 and Step2 in the above code are not legal. But since the execution of the function is the process of its application, if we can implement this mechanism programmatically, for example: var add = function (x, y) {    return x + y;};/ /full applicationadd.apply (null, [5, 4]); 9//partial Applicationvar Newadd = add.partialapply (null, [5]);//Applying an argument to the new functionnewadd.apply (null, [4]); 9
In the above code, PARTIALAPPLY returns a new function, which completes the addition by accepting the remaining arguments. Unfortunately JavaScript does not provide partialapply, so we have to implement it ourselves. 3. Curry (currying)Curry here is not the meaning of curry, but a programming pattern named Haskell Curry, which transforms a regular function into a function that can be stepped up:
A curried Add ()//accepts partial list of argumentsfunction Add (x, y) {    var oldx = x, Oldy = y;    if (typeof oldy = = = "undefined") {//partial        return function (newy) {            return oldx + newy;        };    }    Full application    return x + y;} Testtypeof Add (5); "Function" Add (3) (4); 7//Create and store a new Functionvar add2000 = Add (+); add2000 (10); 2010
With the above code, add can accept either a parameter or two parameters, and when it accepts two arguments, it completes the addition operation; When the parameter has only one, it returns a new function that completes the addition with the first parameter to continue the addition operation during the subsequent execution. The above code can be further reduced by removing OLDX and Oldy:
A curried add//accepts partial list of argumentsfunction Add (x, y) {    if (typeof y = = = "undefined") {//Partial
   return function (y) {            return x + y;        };    }    Full application    return x + y;}
This enables the Add function to be executed in step. Similarly, using the Apply method of a function, you can make a general step-by function:
function Schonfinkelize (FN) {    var slice = Array.prototype.slice,        Stored_args = slice.call (arguments, 1);    return function () {        var New_args = slice.call (arguments),            args = Stored_args.concat (New_args);        return fn.apply (null, args);}    ;}
AboveSchonfinkelize All other elements of arguments except the 1th element (the 1th element is the function name of the curry) are saved in Stored_args by the slice method of array, and then by returning a new function, And to connect some of the previously saved parameters to complete functions of function Division execution:
A normal functionfunction Add (x, y) {    return x + y;} Curry a function to get a new Functionvar Newadd = Schonfinkelize (add, 5); Newadd (4); 9//Another option--Call the new function directlyschonfinkelize (add, 6) (7); 13 can also execute schonfinkelize multiple times, allowing the function to step through multiple steps:/A normal functionfunction add (a, B, C, D, E) {    return a + B + C + D + e;} Works with any number of argumentsschonfinkelize (add, 1, 2, 3) (5, 5); 16//Two-Step Curryingvar AddOne = schonfinkelize (add, 1); AddOne (10, 10, 10, 10); 41var addsix = Schonfinkelize (AddOne, 2, 3); Addsix (5, 5); 16

JavaScript Basics Curry (021)

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.