JavaScript Functional Programming practices (from IBM) 1th-3 page _javascript tips

Source: Internet
Author: User

An introduction to functional programming
When it comes to functional programming, people's first impressions tend to be their academics, obscure, probably only in the way that the heads are distributed, slovenly, and even neurotic college professors do. This may be true at some point in history, but recently, functional programming has been playing a huge role in practical applications, and more and more languages continue to add such as closures, anonymous functions, and so on, to some extent, functional programming is gradually "assimilation" command-type programming.
The source of functional programming thought dates back to the the 1930s, and the mathematician Aaron left. Church is conducting a study of the computable nature of the problem, the later lambda calculus. The essence of a lambda calculus is everything. function, function can be the output of another function or/and input, a series of functions will eventually form a chain of expressions, this expression chain can ultimately find a value, and this process, that is the nature of the calculation.
However, this thought was difficult to achieve on the basis of the hardware of the time, and history finally chose another mathematical theory parallel to Church's lambda theory: Turing as a computational theory, and taking another scientist von. Neumann's computer structure, and is eventually implemented as hardware. Because the first computer is von. Neumann program storage structure, so the program running on this platform also inherits the gene, programming language such as c/pascal and so on to some extent depend on this system.
By the 1950s, a professor at MIT, John McCarthy, was in von. The Neumann system successfully implemented the lambda theory, named LISP (LISt Processor), where the functional programming language became active in the field of computer science.
features of functional programming languages
In a functional programming language, a function is an object of the first class, that is, a function can exist independently of any other object, whereas in an object-oriented language the function (method) is attached to the object and is part of the object. This j determines some of the special properties of the function in the functional language, such as an outgoing/incoming parameter, as an ordinary variable, and so on.
Unlike imperative programming languages, functional programming languages have some proprietary concepts that we discuss separately:
Anonymous Functions
In a functional programming language, a function can have no name, and an anonymous function usually says: "A piece of code that can accomplish something." This expression is useful in many situations because we sometimes need to do something with a function, but the function may be temporary, and there is no reason to create a top-level function object specifically for it. Like what:

Listing 1. Map function

Copy Code code 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//each element of the array [1,3,5,7,8] plus 1

Notice the call to the map function, the second parameter of the map is a function that works for each of the first arguments (arrays) of the map, but the code outside of the map may not have any meaning, so we don't have to define a function specifically for it, and the anonymous function is sufficient.
Corrie
It is the technique of transforming a function that accepts multiple parameters into a function that accepts a single parameter (the first parameter of the original function), and returns a new function that accepts the remaining parameters and returns the result. This sentence is a bit around the mouth, we can use examples to help understand:
Listing 2. The function of the Gerty
Copy Code code 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));

The results are:
6
7
The interesting thing is that the function adder takes a parameter and returns a function that the returned function can be invoked as expected. The variable add5 holds the function returned by the adder (5), which can accept a parameter and return the argument to 5.
Corrie is very useful in the DOM callback, which we'll see in the following sections.
Higher order functions
Higher-order functions are further abstractions of functions, in fact, the map function we mentioned in the anonymous function is a higher order function, which is available in many functional programming languages. The expression of map (array, func) has shown that the Func function is applied to each element in the array, and eventually a new array is returned, and it should be noted that the map's implementation of array and Func is without any prior assumptions, so it is called a "high-order" function:

Listing 3. Higher-order functions
Copy Code code 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 results will be printed:
2,4,6,8,9
(one), (two), (three), (four)//each string in the array with parentheses

Both mapped and MAPPED2 call the map, but they get very different results, because the map parameter itself has been abstracted once, the map function does the second abstraction, and the High-order "order" can be understood as an abstract hierarchy.
functional Programming in JavaScript
JavaScript is a very misunderstood language, because the early WEB development, full of a lot of copy-paste code, so you can usually see the quality of JavaScript code is not high, and JavaScript code is always very flying the constantly flashing GIF wide To limit the duplication of Web content, so many people, including web developers, simply don't want to learn JavaScript.
This situation has been completely reversed in the Ajax Renaissance, and the advent of Ajax apps such as Google Map,gmail makes people wonder: the original JavaScript can do such a thing! Very soon, a lot of good javascript/ajax frameworks, such as Dojo,prototype,jquery,extjs and so on, continue to appear. This code gives the page a gorgeous effect while also allowing the developer to see the elegance of the functional language code.
Functional Programming Style
In JavaScript, the function itself is a special object that belongs to the top-level object and does not depend on any other object, so you can use the function as an outgoing/incoming parameter that can be stored in a variable and what all other objects can do (because the function is the object).
One notable feature of JavaScript as a lisp,lisp code with C syntax is the large number of parentheses and the names of the preceding functions, such as:

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

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

Listing 5. The summation in JavaScript
Copy Code code 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 this code and get the following result:
6
31

If you want to completely simulate the style of functional encoding, we can define something like:

Listing 6. Some simple function abstractions.
Copy Code code 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 b/A;}
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, so that the code we write is more easily accepted by people with functional programming experience:

Current 1/3 page 123 Next read the full text
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.