JavaScript and functional programming explain _JAVASCRIPT skills

Source: Internet
Author: User
Tags closure
Author: Moon Shadow
Keep in mind: Functional programming is not programmed with functions!!!
23.4 Function-type programming
23.4.1 What is functional programming

What is functional programming? If you ask so plainly, you will find that it is a very difficult concept to explain. Many veterans with years of experience in the field of programming do not have a clear idea of what functional programming is all about. Functional programming is indeed a strange field for programmers familiar with procedural programming, closures (closure), continuations (continuation), and Gerty (currying) These concepts seem unfamiliar to us, familiar with if, else, While there is no resemblance. Although functional programming is a graceful mathematical archetype with no procedural analogy, it is so inscrutable that it seems that only people with doctorates can play it.

Tip: This section is a bit difficult, but it's not the skills necessary to master JavaScript, and if you don't want to use JavaScript to complete the esoteric techniques of using Lisp to do work, or don't want to learn functional programming, you can skip them and go on to the next chapter.

So back to this question, what is functional programming? The answer is very long ...

The first law of functional programming: A function is the first type.

How does this sentence itself be understood? What is the real first type? Let's look at the following mathematical concepts:

Guilen f (x, y) = 0,x, y is a variable, write it as Y = F (x), x is a parameter, Y is the return value, F is a mapping relationship from X to Y, and is called a function. If so, g (x, y, Z) = 0, or z = g (x, y), G is the mapping relationship between x, Y and Z, and it is also a function. If G's parameter x, y satisfies the preceding relationship y = f (x), so get z = g (x, y) = g (x, F (x)), there are two meanings, one is f (x) is the function on X, and the other is the parameter of function g, and g is a higher order function than F.
So we use z = g (x, F (x)) to represent the association solution of Equation F (x, Y) = 0 and g (x, y, Z) = 0, which is a function of an iteration. We can also represent G in another form, z = g (x, Y, F), so that we have a function g as a higher order function. The advantage of this latter representation, as compared to the previous one, is that it is a more generalized model, such as the X,y = 0 and g (x,y,z) = 0 Association solutions, which we can also represent in the same form (as long as the f=t). In a language system that supports the transition of a problem to a High-order function iteration, the function is called the "first type".
The function in JavaScript is obviously "first type". The following is a typical example:

Array.prototype.each = function (closure)
{
Return this.length? [Closure (This[0])].concat (This.slice (1). each (closure)): [];
}

This is a magical magic code that fully functions, with functions and symbols (symbol) in the entire code. It is simple in form and powerful.
[1,2,3,4].each (function (x) {return x * 2}) gets [2,4,6,8], and [1,2,3,4].each (function (x) {return x-1}) gets [0,1,2,3].

The essence of function-oriented and object-oriented is "The Tao of Nature". If the object-oriented is a real-world simulation, then the function is the simulation of the mathematical world, in a sense, it is more abstract than the object-oriented, because the mathematical system is inherently more abstract than the nature can match.

Second law of functional programming: Closures are the best friend of functional programming.

Closures, as we've explained in the previous chapters, are important for functional programming. Its greatest feature is that it is not necessary to pass variables (symbols) in the way to directly access the outer layer of the environment, which provides a great convenience for multiple nested functional programs, the following is an example:

(function Outerfun (x)
{
return function Innerfun (y)
{
return x * y;
}
}) (2) (3);

The third law of functional programming: functions can be currying.

What is currying? It's an interesting concept. or starting with math: We say, consider a three-dimensional space equation f (x, y, Z) = 0, and if we qualify z = 0, we get f (x, y, 0) = 0 as F ' (x, y). Here F ' is obviously a new equation that represents a two-dimensional projection of the three-dimensional curve f (x, Y, z) on the z = 0 plane. Remember y = f (x, z), make z = 0, get y = f (x, 0), note y = f ' (x), we say function f ' is a currying solution of F.
Here's a currying example of javascript:
function add (x, y)
{
if (x!=null && y!=null) return x + y;
else if (x!=null && y==null) return function (y)
{
return x + y;
}
else if (x==null && y!=null) return function (x)
{
return x + y;
}
}
var a = Add (3, 4);
var B = Add (2);
var C = B (10);

In the above example, B=add (2) Gets the currying function of an add (), which is when x = 2 o'clock, the function on the parameter y, notice that the closure is also used.

Interestingly, we can generalize currying to arbitrary functions, such as:

function Foo (x, Y, Z, W)
{
var args = arguments;

if (Foo.length < args.length)
return function ()
{
Return
Args.callee.apply (Array.apply ([], args). Concat (Array.apply ([], arguments));
}
Else
return x + y–z * W;
}

The four law of functional programming: deferred evaluation and continuation.
TODO: Consider this again.


Advantages of 23.4.2 Functional programming

Unit Test

Each symbol of strict functional programming is a reference to the direct amount or the result of an expression, and no function produces side effects. Because the value has never been modified somewhere, there is no function that modifies the amount outside its scope and is used by other functions (such as class members or global variables). This means that the result of a function evaluation is only its return value, and the only thing that affects its return value is the parameter of the function.
This is the unit tester's Dream Wonderland (Wet Dream). For each function in the tested program, you only need to care about its parameters, without having to consider the order of function calls without having to carefully set the external state. All you have to do is pass the parameters that represent the marginal situation. If each function in the program passes the unit test, you are confident about the quality of the software. Imperative programming is not so optimistic, in Java or C + + only check the return value of the function is not enough-we must also verify that the function may modify the external state.

Debugging

If a functional program doesn't work as you expect, debugging is easy. Because a bug in a functional program does not rely on a code path that is not relevant before execution, the problem you encounter can always be reproduced. In an imperative program, Bugs come and go, because the function dependencies in the function depend on the side effects of other functions, and you may be searching for a long, fruitless search in the direction unrelated to the bug's creation. This is not the case for a functional program-if the result of a function is wrong, then whatever else you have done before, this function always returns the same error result.
Once you reproduce the problem, finding the root cause will be effortless and will even make you happy. Interrupt the execution of that program and then check the stack, and as with imperative programming, the parameters of every function call in the stack appear in front of you. However, only these parameters are not enough in a command program, and the function also relies on member variables, global variables, and the state of the class (which in turn depends on many of these). In a functional program, a function relies only on its parameters, and that information is under your gaze! Also, in an imperative program, checking only the return value of a function does not convince you that the function is working properly, and you have to look at the state of the dozens of objects that function is scoped to confirm. For a functional program, all you have to do is look at its return value!
Along the stack, check the parameters and return values of the function, and as soon as you find an unreasonable result, go to the function and follow it step-by-step, repeating the process until it lets you find the point of creation of the bug.

Parallel
Functional programs can be executed in parallel without any modification. Don't worry about deadlocks and critical areas, because you never use locks! No data in a functional program is modified two times with the same thread, let alone two different threads. This means that you can simply add threads without thinking about traditional problems that afflict parallel applications.
As a matter of fact, why isn't everyone using functional programs in applications that require highly parallel operations? Well, they're doing it. Ericsson has designed a functional language called Erlang and used it on telecommunication switches that require extremely high error resistance and scalability. Many people have also discovered the advantages of Erlang and started using it. We are talking about telecommunications control systems, which are much higher in reliability and scalability than the typical Wall Street system. In fact, Erlang systems are unreliable and scalable, and JavaScript is. Erlang systems are just rock solid.
The story of parallelism has not stopped, and even if your program itself is single-threaded, the compiler of a functional program can still optimize it to run on multiple CPUs. Take a look at the following code:

String S1 = SomewhatLongOperation1 ();
String s2 = SomewhatLongOperation2 ();
String s3 = concatenate (S1, S2);

In the functional programming language, the compiler analyzes the code, identifies potentially time-consuming functions that create string S1 and S2, and then runs them in parallel. This is not possible in imperative languages, where each function may modify the state outside the function scope and its subsequent functions will depend on those modifications. In functional languages, automatic parsing functions and finding candidate functions suitable for parallel execution are simply like automatic inline functions! In this sense, the functional style of the program is "not obsolete technology (future proof)" (even if you do not like to use industry terminology, but this time to make an exception). Hardware vendors have been unable to run the CPU faster, so they have increased the processor core speed and gained four times times the speed of parallelism. Of course, they also forgot to mention that our extra money was spent on software that solves parallel problems. A small portion of the command software and 100% of functional software can run directly on these machines in parallel.

Code Thermal Deployment

In the past, to install updates on Windows, restarting the computer is unavoidable, and more than once, even if a new version of the media Player is installed. Windows XP has greatly improved this state, but it's still not ideal (I ran Windows Update when I was working today, and now a annoying icon always appears in the tray unless I reboot the machine). UNIX systems have always been running in better mode, and installing updates simply stops the system-related components, not the entire operating system. Even so, for a large server application this is not satisfactory. The telecommunications system must operate 100% of the time, because if the emergency dialing fails when the system is updated, it can cause loss of life. There is no reason for Wall Street companies to stop service on weekends to install updates.
Ideally, any component of the system is not stopped at all to update the associated code. This is impossible in an imperative world. Considering that the runtime uploads a Java class and overloads a new definition, all instances of this class are not available because their saved state is lost. We can solve this problem by writing some cumbersome version control code. It then serializes all instances of the class, destroys the instances, and then uses the new definition of the class to recreate the instances, then load the previously serialized data and hopefully load the code to migrate the data to the new instance. On top of that, each update will have to manually rewrite the code that is used to migrate, and be quite cautious about preventing the interaction between objects. Theory is simple, but practice is not easy.
For functional programs, all the states that pass to the function are stored on the stack, which makes the hot deployment easy! In fact, all we have to do is make a difference comparison between the code in the work and the new version of the code, and then deploy the new code. The rest of the work will be done automatically by a language tool! If you think this is a sci-fi story, please think again. For years, Erlang engineers have been updating their operating systems without interrupting it.

Machine-aided Reasoning and optimization

One interesting attribute of functional languages is that they can be inferred mathematically. Because a functional language is only a form of system implementation, all the operations performed on paper can be applied to programs written in this language. The compiler can use mathematical theory to convert a section of code into an equivalent but more efficient code [7]. For years, relational databases have been doing this kind of optimization. There is no reason why this technique should not be applied to conventional software.
In addition, these techniques can be used to prove that some programs are correct, and may even create tools to analyze code and automatically generate boundary use cases for unit tests! This functionality is not valuable for a solid system, but it is essential if you are designing an atrial pulse generator (pace maker) or an air traffic control system. If you're writing an application that's not a core task for your industry, this kind of tool is also the killer of your competitors.

Disadvantages of 23.4.3 functional programming

Side effects of closures

In non-strict functional programming, closures can overwrite the external environment (as we've seen in the previous chapter), which has side effects that are difficult to track when the side effects are frequent and changes are often made to the program's operating environment.
Todo:

Forms of recursion

Although recursion is usually the most concise form of expression, it is not as intuitive as a recursive loop.
Todo:

Weakness of deferred values

Todo:
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.