A brief discussion on JS functional programming

Source: Internet
Author: User
Tags mul

JS-Functional programming

The idea of function is to use existing functions to assemble new functions.

Functional programming has five distinct features:

1. function is "first Class citizen"
Refers to functions that are equal to other data types

2. Use "expression" only, without "statement"
Expression is a simple arithmetic process, always has a return value;
"Statement" (statement) is an operation that does not return a value.

3. No "Side effects"
Refers to the interaction of functions inside and outside the function (the most typical case is to modify the value of a global variable),
Produces a result other than the operation.

4. Do not modify the status
Variables are often used to hold "state". Does not modify the variable, meaning that the state cannot be stored in the variable,
Functional programming uses parameters to save state

5. Referencing transparency
Refers to the function's run does not depend on the external variable or "state", only depends on the input parameters, any time as long as the parameters are the same,
The return value obtained by the reference function is always the same

The meaning of functional programming:
1. Simple code, rapid development
2. Close to natural language, easy to understand
3. More convenient code management
4. Easy "Concurrent Programming"
5. Hot Upgrade of code

---------------------Split Line------------------------

In JavaScript, the function itself is a special object, which belongs to the top-level object,
exists without relying on any other object, so you can use the function as an outgoing/incoming parameter,
Can be stored in variables, you can do all the other objects can do things.

Self-invoking functions (recursion-self-invocation) are actually a form of higher-order functions.

Functional Programming Examples:

The general implementation of the factorial function factorial (n) {  if (n = = 1) {    return 1;  } else {    return factorial (n-1) * n;}  }  The functional programming style of factorial implements function Mul (A, b) {  return a*b;} function Dec (x) {  return x-1;} function equal (A, B) {  return A==b; } function factorial (n) {  if (equal (n, 1)) {    return 1;  } else {    return mul (n, factorial (Dec (n)  )); }}
---------------------Split Line------------------------
function currying:
is to transform a function that takes multiple arguments into a function that takes a single parameter (the first parameter of the original function),
and returns a technique that takes the remaining parameters and returns the result of the new function.

My understanding is that you need to call a method a () repeatedly, and its parameters have a parameter in a certain condition value is not easy to change,
Each call is written many times too troublesome, but also does not reflect it describes and solve a class of problems, in this case,
To avoid these two problems, we fixed one of the parameters that were not easily changed, and the new one became a function to deal with
This type of problem.
Simple implementation of the addition of Curry:

addition function adder (num) {    return function (x) {      return num + x;    }} var add5 = adder (5), var add6 = adder (6), Console.log (ADD5 (1));//6console.log (ADD6 (1));//7
The ADD5 representation here solves the addition problem with a cardinality of 5, and only needs to pass a parameter.
Instead of having to add two arguments to each call, like a normal addition function.
Computes the N-square var of M powerofn = function (n) {    return function (m) {        var res = 1;        for (var i = 0; i < n; ++i) {            res *= m;        }        return res;    } ;};/ /generate var powerOf2 = powerofn (2), var powerOf3 = powerofn (3),//Call the parameter Console.log (POWEROF2 (3)); Console.log (POWEROF3 (2));
The common implementation of curry:

Function Curry (FN) {    var args = [].slice.call (arguments, 1);    return function () {        var inargs = [].slice.call (arguments);        Console.log (Args.concat (Inargs));        return fn.apply (NULL, Args.concat (Inargs));}    } Function Curry (FN) {    var args = [].slice.call (arguments, 1);    return function () {        var inargs = [].slice.call (arguments);        Console.log (Args.concat (Inargs));        return fn.apply (NULL, Args.concat (Inargs));}    } function Add (NUM1, num2) {    return num1 + num2;} var newadd = Curry (add, 5); Console.log (Newadd (6));
Currying will reduce the universality of function usage, increase the specificity of use, and use curry to carefully identify
Its use of the scene, in accordance with the requirements of the place to use, otherwise it will appear verbose, reduce the readability of the code.
---------------------Split Line------------------------
Higher order functions
A higher-order function is a further abstraction of a function, either as an input to another function, or as a function that returns a function as output.
The most common applications of higher order functions are map (map), Reduce (protocol), ForEach (traversal), filter (filter), etc.
They all manipulate array elements in different ways by passing in different functions.
Simple application:

function foo (f, g) {  return function () {    return f.call (null, g.apply (NULL, arguments));    Return f (g.apply (null, arguments)); It is also possible to  }}var sum = function (x, y) {  return x + y;} var square = function (x) {  return x * x;} var squareofsum = foo (square, sum); Squareofsum (2, 3);//25
Let's look at how to transition from procedural programming to functional programming:

1> form One

var sum = function (x, y) {  return x + y;} var square = function (x) {  return x * x;} function foo () {  return square (SUM (2, 3));} Foo ();//25
2> Form II

var sum = function (x, y) {  return x + y;} var square = function (x) {  return x * x;} function foo (f, g) {  return F (g (2, 3));} Foo (square, sum);//25
3> Form III

var sum = function (x, y) {  return x + y;} var square = function (x) {  return x * x;} function foo (f, g) {  return function () {    var num1 = arguments[0];    var num2 = arguments[1];    Console.log (NUM1, num2);//2 3    var temp = g (NUM1, num2);    Console.log (temp);//5    return F (temp);}  ;} var myfunc = foo (square, sum); MyFunc (2, 3);//25
4> Form IV

var sum = function (x, y) {  return x + y;} var square = function (x) {  return x * x;} function foo (f, g) {  return function () {    var temp = g.apply (null, arguments);    return f (temp);  };} var myfunc = foo (square, sum); MyFunc (2, 3);//25
The final form four is the effect we want to get.

---------------------Split Line------------------------
Other examples:

1>

function foo (FN, array, value) {  var res = Array.map (function (ele) {    return fn.apply (null, [Ele].concat (value));  });  return res;} function add (x, y) {  return x + y;} function sub (x, y) {  return x-y;} Console.log (foo (add, [1, 2, 3], 3));//[4, 5, 6]console.log (foo (Sub, [1, 2, 3], 3));//[-2,-1, 0]

2>

function Multicast (FN) {  return function () {    var pre = arguments[0];    var rest = arguments[1];    var ret = Pre.map (function (ele) {      return fn.apply (This, [Ele].concat (rest));    });    return ret;  }} function add (x, y) {  return x + y;} var Newadd = Multicast (add), Console.log (Newadd ([1,2,3],3));//[4, 5, 6]function Sub (x, y) {return x-  y;} var NewSub = Multicast (sub); Console.log (NewSub ([1,2,3],3));//[-2,-1, 0]

Resources:

Https://blog.oyanglul.us/javascript/functional-javascript.html

http://www.phodal.com/blog/javascript-higher-order-functions/

Http://www.cnblogs.com/wing011203/archive/2013/07/07/3176641.html

http://www.ibm.com/developerworks/cn/web/1006_qiujt_jsfunctional/

Http://www.cnblogs.com/pigtail/p/3447660.html

Http://www.ruanyifeng.com/blog/2012/04/functional_programming.html

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

A brief discussion on JS functional programming

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.