Home > Web Front-end > JS Tutorial > Functional programming using JavaScript (1) Translation_javascript skills

Functional programming using JavaScript (1) Translation_javascript skills

PHP中文网
Release: 2016-05-16 15:37:31
Original
1104 people have browsed it

Programming Paradigm

A programming paradigm is a framework composed of tools for thinking about a problem and realizing a vision for the problem. Many modern languages ​​are polyparadigm (or multi-paradigm): they support many different programming paradigms, such as object-oriented, metaprogramming, functional, procedural, etc.

Functional programming using JavaScript (1) Translation_javascript skills

Functional Programming Paradigm

Functional programming is like a hydrogen-powered car - advanced futuristic, But it has not been widely promoted. In contrast to imperative programming, it consists of a sequence of statements that update the global state at execution time. Functional programming turns calculations into expression evaluations. These expressions are all composed of pure mathematical functions, which are first-class (can be used and processed as normal values) and have no side effects.

Functional programming using JavaScript (1) Translation_javascript skills

Functional programming values ​​​​the following values:

Functions are first priority

We should treat functions Treated like other class objects in programming languages. In other words, you can store functions in variables, create functions dynamically, and return functions or pass functions to other functions. Let's look at an example...

Functional programming using JavaScript (1) Translation_javascript skills

A string can be saved as a variable, and so can functions, for example:


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

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

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

A string can be created only when it is needed again, and so can a function, for example:

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

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

    function hellloWorld(hello, world) { return hello + world() }
Copy after login

A string can be used as a function return value, and the function can also do it, for example:

return “Hello”;
return function() { return “Hello”};
Copy after login

High-order case

Functional programming using JavaScript (1) Translation_javascript skills

If a function takes other functions as input parameters or as return values, it is called higher-order function. We have just seen an example of a higher-order function. Next, let's look at a more complex situation.

Example 1:

[1, 2, 3].forEach(alert);
// alert 弹窗显示“1" 
// alert 弹窗显示 "2" 
// alert 弹窗显示 "3”
Copy after login

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
Copy after login

FavoritesPure functions


Pure Functions


Pure functions will not have other side effects. The so-called side effects refer to the modification of the external state of the function caused by the function. For example:

  • Modify a variable

  • Modify the data structure

  • Modify a variable from the outside world Set a field

  • Throw an exception or pop up an error message

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


Avoid modifying state

Pure functions cannot mutate data

Functional programming supports pure functions, which cannot change data , so it is mostly used to create immutable data. In this way, there is no need to modify an existing data structure, and it can efficiently create a new one.
You may want to know if a pure function produces an immutable return value by changing some local data, is it allowed? of? The answer is yes.
Very few data types in JavaScript are immutable by default. String is an example of a data type that cannot be changed:

   var s = "HelloWorld";
    s.toUpperCase();
    //=> "HELLOWORLD"
    s;
    //=> "HelloWorld"
Copy after login

Benefits of immutable state

• Avoid confusion and increase program accuracy: In complex systems, Most obscure bugs are caused by state being modified by external client code in the program.
• 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.
Software transactional memory and the Actor model provide direct processing of modifications in a thread-safe manner.

Use recursion instead of loop calls

Functional programming using JavaScript (1) Translation_javascript skills

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

替代反复循环的最经典方式就是使用递归,即每次完成函数体操作之后,再继续执行集合里的下一项,直到满足结束条件。递归还天生符合某些算法实现,比如遍历树形结构(每个树枝都是一颗小树)。

在任何语言里,递归都是一项重要的函数式编程方式。很多函数语言甚至要求的更加严格:只支持递归遍历,而不支持显式的循环遍历。这需要语言必须保证消除了尾端调用,这是 JavasSrip 不支持的。

惰性求值优于激进计算

Functional programming using JavaScript (1) Translation_javascript skills

数学定义了很多无穷集合,比如自然数(所有的正整数)。他们都是符号表示。任意特定有限的子集都在需要时求值。我们将其称之为惰性求值(也叫做非严格求值,或者按需调用,延迟执行)。及早求值会强迫我们表示出所有无穷数据,而这显然是不可能的。

很多语言都默认是惰性的,有些也提供了惰性数据结构以表达无穷集合,并在需要时对自己进行精确计算。

很明显一行代码 result = compute() 所表达的是将 compute() 的返回结果赋值给 result。但是 result 的值究竟是多少只有其被用到的时候才有意义。

可见策略的选择会在很大程度上提高性能,特别是当用在链式处理或者数组处理的时候。这些都是函数式程序员所喜爱的编程技术。

这就开创可很多可能性,包括并发执行,并行技术以及合成。

但是,有一个问题,JavaScrip 并不对自身进行惰性求值。话虽如此,Javascript 里的函数库可以有效地模拟惰性求值。

闭包的全部好处

所有的函数式语言都有闭包,然而这个语言特性经常被讨论得很神秘。闭包是一个函数,这个函数有着对内部引用的所有变量的隐式绑定。换句话说,该函数对它引用的变量封闭了一个上下文。JavaScript 中的闭包是能够访问父级作用域的函数,即使父级函数已经调用完毕。

   function multiplier(factor) {
      return function(number) {
          return number * factor;
      };
   }
  var twiceOf = multiplier(2);
    console.log(twiceOf(6));
//=> 12
Copy after login

声明式优于命令式编程

函数式编程是声明式的,就像数学运算,属性和关系是定义好的。运行时知道怎么计算最终结果。阶乘函数的定义提供了一个例子:

factorial(n) = 1 if n = 1

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

该定义将 factorial(n) 的值关联到 factorial(n-1),是递归定义。特殊情况下的 factorial(1) 终止了递归。

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);
      }
  }
Copy after login

从它实现阶乘计算来看,声明式的阶乘可能看起来像“命令式”的,但它的结构更像声明式的。

命令式阶乘使用可变值、循环计数器和结果来累加计算后的结果。这个方法显式地实现了特定的算法。不像声明式版本,这种方法有许多可变步骤,导致它更难理解,也更难避免 bug 。

Functional programming using JavaScript (1) Translation_javascript skills

函数式JavaScript库

有很多函数式库:underscore.js, lodash,Fantasy Land, Functional.js, Bilby.js, fn.js, Wu.js, Lazy.js, Bacon.js, sloth.js, stream.js, Sugar, Folktale, RxJs 等等。

函数式程序员工具包

map(), filter(), 和 reduce()函数 构成了函数式程序员工具包的核心。 纯高阶函数成了函数式方法的主力。事实上,它们是纯函数和高阶函数应该仿效的典型。它们用一个函数作为输入,返回没有副作用的输出。

这些 JavaScript 函数对每一个函数式程序来说都是至关重要的。他们可以去除循环和语句,使得代码更加整洁。这些都是实现 ECMAScript5.1 的浏览器的标准,他们只处理数组。每次调用都会创建创建并返回一个新的数组。已存在的数组不会被修改。但是稍等,事情很不止于此。。。他们还将函数作为输入参数,通常是作为回调的匿名函数。他们会遍历将整个数组并且将该回调函数应用与每一项!

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]

除了这三个函数,还有很多函数可以扎入到几乎每一个函数式应用里:

forEach(),concat(), reverse(), sort(), every() 以及some().

JavaScript'sGatheringPardigms

JavaScript is of course not a functional programming language in the strict sense, which also prompts a focus on other paradigms Usage:

  • Imperative programming: programming based on detailed operation descriptions

  • Prototype-based object-oriented programming: based on prototype objects and Programming of its examples

  • Metaprogramming: a programming method that manipulates the JavsScript execution model. A good definition of metaprogramming describes it as “Programming happens when you write code to do something, while metaprogramming happens when you write code that causes a change in the way something is interpreted.

The above is the content of using JavaScript for functional programming (1) translation_javascript skills. For more related content, please pay attention to the PHP Chinese website (www.php.cn)! 🎜>

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template