Using JavaScript for Functional Programming (i) Translation _javascript skills

Source: Internet
Author: User
Tags closure data structures mathematical functions

Programming paradigm

The programming paradigm is a framework that consists of thinking about problems and realizing the vision of a problem. Many modern languages are clustering paradigms (or multiple paradigms): They support many different programming paradigms, such as object-oriented, meta programming, functional, process-oriented, and so on.


Functional Programming Paradigm

Functional programming is like a hydrogen-fueled car-an advanced futuristic, but not yet widely promoted. Instead of imperative programming, he consists of a series of statements that are used to update the global state at execution time. Functional programming transforms the computation into an expression evaluation. These expressions are all composed of pure mathematical functions, which are first-rate (can be used and processed as a general value) and have no side effects.

Functional programming attaches great importance to the following values:

function is a first-class task

We should treat the function in the same way as other class objects in the programming language. In other words, you can store functions in variables, create functions dynamically, return functions, or pass functions to other functions. Now let's take a look at an example ...

A string can be saved as a variable, and the function can also, for example:

var SayHello = function () {return "Hello"};

A string can be saved as an Object field, and a function can also, for example:

var person = {message: ' Hello ', sayhello:function () {return ' Hello '}};

A string can be created again, and the function can, for example:

"Hello" + (function () {return ' World '}) (); => Hello World

A string can be passed as an input parameter to a function, the function can also:

function Hellloworld (Hello, world) {return Hello + world ()}

A string can return a value as a function, and the function can also, for example:

return "Hello";
return function () {return "Hello"};

High-order case

If a function takes another function function as an input parameter or as a return value, it is called a high-order function. Just now we have seen an example of a higher order function. Next, let's look at more complex situations.

Example 1:

[1, 2, 3].foreach (alert);
Alert window Display "1"
//Alert Bullet window Display "2"
//Alert window display "3"

Example 2 :

function Splat (fun) {return
function (array) {return
fun.apply (null, array);
};
}
var addarrayelements = Splat (function (x, y) {return x + y});
Addarrayelements ([1, 2]);
=> 3

most Love Pure Function


Pure functions do not have other side effects, the so-called side effects refers to the function generated by the function of the external state of the changes. Like what:

    • Modify a variable

    • modifying data structures

    • Set a field on a variable outside

    • Throw an exception or eject an error message

The simplest example is the mathematical function. The MATH.SQRT (4) function always returns 2. He would not use any other chilling information, such as state or set parameters. Mathematical functions never cause any side effects.


Avoid modification status

Functional programming supports pure functions that do not change data, so most are used to create immutable data. This way, you don't have to modify an existing data structure, and you can create a new one efficiently.
You might want to know if a pure function produces an immutable return value by altering some local data, is it permissible? The answer is yes.
A very small number of data types in JavaScript are not immutable by default. String is an example of a data type that cannot be changed:

var s = "HelloWorld";
S.touppercase ();
=> "HELLOWORLD"
s;
=> "HelloWorld"

The benefits of not changing the state

• Avoid confusion and increase the accuracy of the program: in complex systems, most of the bugs that are difficult to understand are caused by changes in the state's external client code in the program.
• Establish "Fast and concise" multithreaded programming: If multithreading can modify the same shared value, you have to synchronize to get the value. This is a tedious and error-prone programming challenge for experts.
The software transaction memory and Actor model provides a direct thread-safe way to process modifications.

Using recursion instead of circular calls

Recursion is the most famous functional programming technique. If you don't know it yet, then you can understand that a recursive function is a function that can call itself.

The classic way to replace recurring loops is to use recursion, which means that after each function gymnastics is completed, the next item in the collection is executed until the end condition is met. Recursion is inherently consistent with certain algorithms, such as traversing a tree (each branch is a small tree).

In any language, recursion is an important functional programming method. Many function languages are even more stringent: only recursive traversal is supported, not explicit loop traversal. This requires that the language must ensure that the end call is eliminated, which is not supported by Javassrip.

Lazy evaluation is better than radical calculation

Mathematics defines a number of infinite sets, such as natural numbers (all positive integers). They are all symbolic representations. Any given limited subset is evaluated when it is needed. We call it lazy evaluation (also called a non rigorous evaluation, or on-demand invocation, deferred execution). Early evaluation forces us to represent all the infinite data, which is obviously impossible.

Many languages are lazy by default, and some also provide lazy data structures to express an infinite set and accurately compute for themselves when needed.

It is clear that a line of code result = Compute () is an expression that assigns the return results of compute () to result. But the value of result is only meaningful when it is used.

The choice of visible strategies can greatly improve performance, especially when used in chain processing or array processing. These are the programming techniques that functional programmers love.

This creates many possibilities, including concurrent execution, concurrent technology, and compositing.

However, there is a problem that Javascrip does not evaluate itself lazily. That being said, a function library in Javascript can effectively simulate lazy evaluation.

The full benefits of closures

All functional languages have closures, but this linguistic feature is often discussed in mysterious detail. A closure is a function that has an implicit binding to all variables that are referenced internally. In other words, the function encloses a context for the variable it references. A closure in JavaScript is a function that can access the parent scope, even if the parent function has already been called.

Function multiplier (factor) {return
function (number) {return number
* factor;
};
var twiceof = multiplier (2);
Console.log (twiceof (6));
=> 12

Declarations are better than command-style programming

Functional programming is declarative, just like mathematical operations, attributes, and relationships are defined well. The runtime knows how to calculate the final result. The definition of a factorial function provides an example:

Factorial (n) = 1 if n = 1

n * Factorial (n-1) if n > 1

The definition associates the value of factorial (n) to factorial (n-1), which is a recursive definition. The factorial (1) In special cases terminates recursion.

Var imperativefactorial = function (n)  {    if (n == 1)  {         return 1     } else { 
       product = 1;         for (i = 1; i <= n; i++)  
{              product *= i;         }         return 
Product &NBSP;&NBSP;&NBSP;&NBSP;&NBSP}} var declarativefactorial = function (n)  {        if (n == 1)  {              return 1        } else {              return n * factorial (n - 1);       }   }

From the point of view of factorial calculation, the factorial of a declarative may look like a "command", but its structure is more like a declarative type.

Imperative factorial uses variable values, loop counters, and results to accumulate the computed results. This method explicitly implements a particular algorithm. Unlike declarative versions, this approach has many variable steps that make it harder to understand and more difficult to avoid bugs.

Functional JavaScript Libraries

There are many functional libraries: Underscore.js, Lodash,fantasy Land, Functional.js, Bilby.js, Fn.js, Wu.js, Lazy.js, Bacon.js, Sloth.js, Stream.js, Sugar, folktale, RXJS and so on.

Functional Programmer Toolkit

The map (), filter (), and reduce () functions form the core of the Functional Programmer toolkit. Pure higher-order functions are the main force of functional methods. In fact, they are typical of pure functions and higher-order functions that should be emulated. They use a function as input to return output without side effects.

These JavaScript functions are critical to every functional program. They can remove loops and statements, making the code cleaner. These are the standards for implementing ECMAScript5.1 browsers, and they only handle arrays. Each call creates and returns a new array. An array that already exists will not be modified. But wait a minute, it's more than that ... They also use functions as input parameters, usually as anonymous functions for callbacks. They will iterate over the entire array and apply the callback function to each item!

MyArray = [1,2,3,4];

NewArray = Myarray.map (function (x) {return x*2});

Console.log (myarray); Output: [1,2,3,4]

Console.log (NewArray); Output: [2,4,6,8]

In addition to these three functions, there are many functions that can be stuck into almost every functional application:

ForEach (), concat (), reverse (), sort (), every (), and some ().

of JavaScript Poly Paradigm

JavaScript is certainly not a functional programming language in the strictest sense, which also prompts the use of other paradigms:

    • Imperative programming: Programming based on detailed operational descriptions

    • Object-oriented programming based on prototype: programming based on prototype object and its instance

    • Metaprogramming: The programmatic way to manipulate the Javsscript execution model. A good definition of metaprogramming is described as "programming occurs when you write code to do something, and metaprogramming occurs when you write code that causes something to change in the way it is interpreted."

Original address: Https://dzone.com/articles/functional-programming-using-javascript-part-1

Translation: simei231, Zhu Qing, Li Zhongkai

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.