Functional programming using JavaScript (I) _ javascript skills

Source: Internet
Author: User
Tags mathematical functions
This is the first article in the functional programming series. Here I will briefly introduce the programming paradigm, and then I will directly introduce the concept of functional programming using Javascript, because JavsScript is one of the most recognized functional programming languages. We encourage readers to learn more about this fascinating concept through references. Programming Paradigm

The programming paradigm is a framework composed of tools for thinking about problems and realizing the vision of problems. Many modern languages use clustering paradigms (or multiple paradigms): they support many different programming paradigms, such as object-oriented, metaprogramming, functional, process-oriented, and so on.

var sayHello = function() { return “Hello” };

A string can be saved as an object field, or a function, for example:

var person = {message: “Hello”, sayHello: function() { return “Hello” }};

A string can be created only when it can be used. The function can also be used, for example:

“Hello ” + (function() { return “World” })(); //=> Hello World

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

    function hellloWorld(hello, world) { return hello + world() }

A string can be returned as a function, or a function, for example:

return “Hello”;return function() { return “Hello”};
Advanced Cases

Example 1:

[1, 2, 3]. forEach (alert); // The alert pop-up window shows "1" // The alert pop-up window shows "2" // The alert pop-up window shows "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

FavoritesPure Function



Pure functions do not have any other side effects. The so-called side effects refer to the changes made by the function to the external state of the function. For example:

  • Modify a variable

  • Modify Data Structure

  • Set a field for a variable

  • Throw an exception or pop-up error message

The simplest example is a mathematical function. The Math. sqrt (4) function always returns 2. It does not use any other cold information, such as status or set parameters. Mathematical functions never have any side effects.


Avoid modifying the status

Function programming supports pure functions. Such functions cannot change data, so most of them are used to create unchangeable data. In this way, you do not need to modify an existing data structure, and you can efficiently create a new one.
You may want to know if a pure function can generate an unchangeable return value by changing some local data? The answer is yes.
In JavaScript, very few data types are unchangeable by default. String is an example of a data type that cannot be changed:

   var s = "HelloWorld";    s.toUpperCase();    //=> "HELLOWORLD"    s;    //=> "HelloWorld"
Benefits of unchangeable status

• Avoid confusion and increase program accuracy: in a complex system, most bugs that are hard to understand are caused by modifications to the state of the external client code in the program. Bytes
• Establish fast and concise multi-threaded programming: if multiple threads can modify the same shared value, you have to get the value synchronously. This is a tedious and error-prone programming challenge for experts. Bytes
The software transaction memory and Actor Model provide direct processing and modification in thread-safe mode.

Use recursion instead of loop call

Mathematics defines many infinite sets, such as natural numbers (all positive integers ). They are all symbolic representations. Any specific finite subset is evaluated as needed. We call it an inert evaluate (also called a non-strict evaluate, or call as needed, delayed execution ). Early Evaluation forces us to express all infinite data, which is obviously impossible.

Many languages are inert by default, and some also provide an inert data structure to express infinite sets, and perform precise calculations on themselves as needed.

Obviously, a line of codeResult = compute ()The expression isCompute ()The returned result is assigned to result. However, the value of result is meaningful only when it is used.

Visible Policy Selection will greatly improve the performance, especially when used in chain processing or array processing. These are the programming technologies that function programmers love.

This creates many possibilities, including concurrent execution, parallel technology, and synthesis.

However, there is a problem that commit Crip does not evaluate its inertia. Even so, the function library in Javascript can effectively simulate the value of inertia.

All the benefits of closures

All functional languages have closures, but this feature is often discussed mysteriously. A closure is a function that has an implicit binding to all variables referenced internally. In other words, the function closes a context for the variables it references. Closure in JavaScript is a function that can access the parent-level scope, even if the parent-level function has been called.

   function multiplier(factor) {      return function(number) {          return number * factor;      };   }  var twiceOf = multiplier(2);    console.log(twiceOf(6));//=> 12
Declarative Programming is better than imperative Programming

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

Factorial (n) = 1 if n = 1

N * factorial (n-1) if n> 1

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

var imperativeFactorial = function(n) {    if(n == 1) {        return 1    } else {        product = 1;        for(i = 1; i <= n; i++) {              product *= i;        }        return product;     }}var declarativeFactorial = function(n) {       if(n == 1) {             return 1       } else {             return n * factorial(n - 1);      }  }

From its implementation of factorial calculation, declarative factorial may look like a "imperative", but its structure is more like declarative.

The numerator factorial uses variable values, cyclic counters, and results to accumulate the calculated results. This method explicitly implements specific algorithms. Unlike declarative versions, this method has many Variable Steps, making it harder to understand and avoid bugs.

The above is the use of JavaScript for functional programming (1) Translation _ javascript skills content, for more information, please follow the PHP Chinese Network (www.php1.cn )!

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.