Page 1/3 of JavaScript functional programming practices (from IBM)

Source: Internet
Author: User

Introduction to functional programming
When it comes to functional programming, people often make the first impression of their academic school, which is obscure. It is probably the only programming method that is used by university professors who are undisciplined, unmasked, or even nervous. This may be true at a certain stage in history, but function programming has played a huge role in practical applications recently, and more languages are constantly adding closures, to some extent, functional programming is gradually "assimilation" imperative programming.
The source of functional programming can be traced back to the 1930s S. The mathematician Alan Qiu Qi was conducting a research on the calculability of the problem, that is, the later lambda algorithm. Lambda calculus is essentially a function. A function can be used as an output or/or input of another function. When a series of functions are used, an expression chain is formed, this expression chain can finally obtain a value, and this process is the essence of computing.
However, this idea was difficult to implement on the basis of the hardware at that time. In history, we finally chose another mathematical theory parallel to the lambda theory of Qiu Qi: the Turing machine as the computing theory, and take another scientist Feng. noriman's computer structure was eventually implemented as hardware. Because the first computer is Feng. noriman's program storage structure, so the program running on this platform also inherits this gene, and programming languages such as C/Pascal depend to some extent on this system.
In 1950s, John McCarthy, a professor at MIT, went to Feng. lambda theory was successfully implemented on the machine of the noriman system and named it "LISt Processor". Now functional programming languages have become active in the computer science field.
Functional Programming Language Features
In functional programming languages, a function is the first type of object. That is to say, a function can exist independently without any other object. In object-oriented languages, functions (methods) are attached to objects and are part of objects. This j determines some special properties of a function in a functional language, such as an outgoing/incoming parameter and a common variable.
Unlike imperative programming languages, functional programming languages have some special concepts. We will discuss them separately:
Anonymous Functions
In functional programming languages, a function can have no name. An anonymous function usually indicates "a piece of code that can accomplish something ". This expression is useful in many cases, because we sometimes need to use a function to accomplish something, but this function may be temporary, there is no reason to generate a top-level function object. For example:

Listing 1. map Functions
Copy codeThe Code is as follows:
Function map (array, func ){
Var res = [];
For (var I = 0, len = array. length; I <len; I ++ ){
Res. push (func (array [I]);
}
Return res;
}
Var mapped = map ([1, 3, 5, 7, 8], function (n ){
Return n = n + 1;
});
Print (mapped );
Running this code will print:
2, 4, 6, 8, 9 // Add 1 to each element in the array [1, 3, 5, 7, 8]

Note the call of the map function. The second parameter of map is a function. This function has an effect on each of the first parameters (arrays) of map, but it may have no significance for code other than map. Therefore, we do not need to define a function for it. Anonymous functions are enough.
Kerihua
Curialization converts a function that accepts multiple parameters into a function that accepts a single parameter (the first parameter of the initial function, and return the technology of the new function that accepts the remaining parameters and returns results. This sentence is a bit difficult. We can use examples to help you understand it:
List 2. colized Functions
Copy codeThe Code is as follows:
Function adder (num ){
Return
Function (x ){
Return num + x;
}
}
Var add5 = adder (5 );
Var add6 = adder (6 );
Print (add5 (1 ));
Print (add6 (1 ));

Result:
6
7
Interestingly, the adder function accepts a parameter and returns a function, which can be called as expected. The variable add5 maintains the function returned by adder (5). This function can accept a parameter and return the sum of the parameter and 5.
Kerialization is very useful in DOM callback. We will see it in the following section.
High-order functions
High-order functions are further abstract functions. In fact, the map function we mentioned in the anonymous function section is a high-order function, which is available in many functional programming languages. The expression of map (array, func) indicates that the func function is applied to every element in the array and a new array is returned. Note that, map's implementation of array and func does not have any pre-assumptions, so it is called a "high-order" function:

Listing 3. High-Order Functions
Copy codeThe Code is as follows:
Function map (array, func ){
Var res = [];
For (var I = 0, len = array. length; I <len; I ++ ){
Res. push (func (array [I]);
}
Return res;
}
Var mapped = map ([1, 3, 5, 7, 8], function (n ){
Return n = n + 1;
});
Print (mapped );
Var mapped2 = map (["one", "two", "three", "four"],
Function (item ){
Return "(" + item + ")";
});
Print (mapped2 );


The following result is printed:
2, 4, 6, 8, 9
(One), (two), (three), (four) // brackets each string in the array

Both mapped and mapped2 call map, but the results are quite different, because map parameters have already been abstracted once, and map functions are abstracted for the second time, A higher level can be understood as an abstract level.
Functional Programming in JavaScript
JavaScript is a widely misunderstood language. Because it was full of a lot of copy-paste code in early Web development, the quality of JavaScript code is usually not high, in addition, JavaScript code is constantly flashing gif advertisements, limiting the replication of webpage content and so on. Therefore, many people, including Web developers, are reluctant to learn JavaScript.
This situation was completely reversed in the Ajax renaissance. The emergence of Google Map, Gmail, and other Ajax applications surprised people that JavaScript could still do this! Soon, a large number of excellent JavaScript/Ajax frameworks were emerging, such as Dojo, Prototype, jQuery, and ExtJS. These codes bring brilliant results to the page, while allowing developers to see the elegance of functional language code.
Functional programming style
In JavaScript, a function itself is a special object that belongs to a top-level object and does not depend on any other object. Therefore, a function can be used as an outgoing/incoming parameter and stored in a variable, and everything that other objects can do (because a function is an object ).
JavaScript is called LISP with C syntax. A notable feature of LISP code is a large number of parentheses and the front function names, such:

Listing 4. Addition in LISP
(+ 1 3 4 5 6 7)

The plus sign is a function in LISP. This expression means to add all the numbers behind the plus sign and return the value. JavaScript can define the same sum function:

Listing 5. sum in JavaScript
Copy codeThe Code is as follows:
Function sum (){
Var res = 0;
For (var I = 0, len = arguments. length; I <len; I ++ ){
Res + = parseInt (arguments [I]);
}
Return res;
}
Print (sum (1, 2, 3 ));
Print (sum (1, 2, 3, 4, 6, 7, 8 ));

Run the code to obtain the following results:
6
31

To fully simulate the functional encoding style, we can define the following:

Listing 6. Some simple function abstractions
Copy codeThe Code is as follows:
Function add (a, B) {return a + B ;}
Function sub (a, B) {return a-B ;}
Function mul (a, B) {return a * B ;}
Function div (a, B) {return a/B ;}
Function rem (a, B) {return a % B ;}
Function inc (x) {return x + 1 ;}
Function dec (x) {return x-1 ;}
Function equal (a, B) {return a = B ;}
Function great (a, B) {return a> B ;}
Function less (a, B) {return a <B ;}

Such small functions and predicates make it easier for people with functional programming experience to write 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.