Analysis of javascript functional programming examples

Source: Internet
Author: User

Analysis of javascript functional programming examples

This article mainly introduces javascript functional programming. The example analyzes the usage skills related to javascript functional programming, which is very useful. For more information, see

This example describes javascript functional programming. Share it with you for your reference. The specific analysis is as follows:

Javascript can write higher-order functions like other dynamic languages. The so-called higher-order functions can operate functions. In JavaScript, functions are a thorough object and belong to the first type of citizens. This provides a prerequisite for functional programming.

The following is an example code from a js tutorial. The function is to calculate the average value and standard deviation of array elements. First, it lists a method of non-functional programming:

?

1

2

3

4

5

6

7

8

9

10

11

12

Var data = [1, 1, 3, 5, 5];

Var total = 0;

For (var I = 0; I <data. length; I ++)

Total + = data [I];

Var mean = tatal/data. length; // The average is 3

// Calculate the standard deviation

Total = 0;

For (var I = 0; I <data. length; I ++ ){

Var deviation = data [I]-mean;

Tatal + = deviation * deviation;

}

Var stddev = Math,. sqrt (total/(data. length-1); // standard deviation is 2

To use function-based programming, We pre-define some help functions (helper functions ):

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

// Convert the class array object to a real Array

Function array (a, n ){

Return Array. prototype. slice. call (a, n | 0 );

}

// Pass the function arguments to the left

Function partial_left (f ){

Var args = arguments;

Return function (){

Var a = array (args, 1 );

A = a. concat (array (arguments ));

Return f. apply (this, );

};

}

// Pass the real parameters of the function to the right

Function partial_right (f ){

Var args = arguments;

Return function (){

Var a = array (arguments );

A = a. concat (array (args, 1 ));

Return f. apply (this, );

};

}

// This function real parameter is used as a template,

// The undefined value in the real parameter list will be filled with the actual real parameter value.

Function partial (f ){

Var args = arguments;

Return function (){

Var a = array (args, 1 );

Var I = 0, j = 0;

For (; I <a. length; I ++)

If (a [I] === undefined)

A [I] = arguments [j ++];

A = a. concat (array (arguments, j ));

Return f. apply (this, );

};

}

// Returns a function similar to f (g ())

Function compose (f, g ){

Return function (){

Return f. call (this, g. apply (this, arguments ));

};

}

The following is the JavaScript code fully programmed using functions:

?

1

2

3

4

5

6

7

8

9

10

Var data = [1, 1, 3, 5, 5];

Var sum = function (x, y) {return x + y ;};

Var product = function (x, y) {return x * y ;};

Var neg = partial (product,-1 );

Var square = partial (Math. pow, undefined, 2 );

Var sqrt = partial (Math. pow, undefined, 0.5 );

Var reciprocal = partial (Math. pow, undefined,-1 );

// Okay, climax :)

Var mean = product (reduce (data, sum), reciprocal (data. length ));

Var stddev = sqrt (product (reduce (map (data, compose (square, partial (sum, neg (mean), sum), reciprocal (sum (data. length,-1 ))));

In addition to the reduce and map functions, other functions are described earlier. The reduce function is similar to the inject function in ruby:

?

1

2

Ary = (1 .. 10). to_a

Ary. inject (0) {| sum, I | sum + I} // The result is 55.

Js is written as follows:

?

1

2

3

4

Var ary = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Ary. reduce (function (sum, I ){

Return sum + I;

}, 0 );

0 is the initial value of sum. If it is omitted, sum is the value of the first element of the array, which can be omitted here.

The map function is also very simple. It is similar to performing operations on every element of the array and then returning an array after the operation. Taking the ruby code as an example, the js Code is similar to this:

?

1

2

A = (1 .. 3). to_a; # array [1, 2, 3]

A. map {| x * 2} # returns the new array [2, 4, 6].

Next we will analyze the long string of code :)

Sum and product define the function of adding and multiplying elements;

Neg is also a function equivalent to: product (-1, x), that is, evaluate the negative value of x;

The square function is equivalent to Math. pow (x, 2) is used to calculate the square value of x. Note that the second parameter of partial is undefined, which means that the parameter is filled by the first real parameter; here we can understand that the square (x) function is equal to Math. pow (x, 2 ).

The sqrt function is similar to square, and its function is equivalent to Math. pow (x, 0.5), which is equivalent to the open quadratic side of x.

The last function, reciprocal, has no difficulty. It is equivalent to Math. pow (x,-1), that is, calculating the negative cubic of x, which is equivalent to calculating the reciprocal of x.

The following is how to knead the above functions together :)

First, let's look at the calculation of the average value. It is very simple: Calculate the sum of the array elements and then multiply the reciprocal of the array length, that is, the length of the array and/array.

Finally, it seems difficult to calculate the standard deviation. We 'd better look at it from the inside out:

First look at the layer that contains the neg:

?

1

2

// Equivalent to the sum (-1 * mean + x) Function)

Partial (sum, neg (mean)

The following describes the compose function:

?

1

2

3

4

// The following is an equivalent replacement in the source code, which can be equivalent again:

// Square (sum (-1 * mean + x), expand again (I peel, I peel, I peel onions ...):

// Math. pow (sum (-1 * mean + x), 2 );

Compose (square, sum (-1 * mean + x ))

Next, let's look at the map function:

// Is it clear !? That is, each element in data is an x, which is passed into the following function, and then a new calculated array is returned, that is, the value of each element in the new array is the mean of adding a negative data to each element in data, and then the result is calculated to the power of 2.

?

1

Map (data, Math. pow (sum (-1 * mean + x), 2 ))

Next, let's look at the reduce function outside map:

?

1

2

// Add each element value of the new array.

Reduce (map (...), sum)

Then let's take a look at the reciprocal function:

?

1

2

// Equivalent to the reciprocal of (data. length-1)

Reciprocal (sum (data. length,-1 ))

Let's look at the outer product function:

?

1

2

// Equivalent to the sum of elements in the new array divided by (data. length-1)

Product (reduce (...), reciprocal (...))

The sqrt at the outermost layer calculates the square root of the result obtained by the above division. You can compare the code of the previous non-function programming with the same result. :) a huge amount of code that looks quite scary, after analysis, the difficulty is immediately reduced. If you still haven't understood what the audience finally said, it is a question about the language expression ability of the cat. You are welcome to ask questions.

The explanation is complete, and the success is done.

I hope this article will help you design javascript programs.

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.