Javascript functional programming language _ javascript skills

Source: Internet
Author: User
JavaScript is a very popular programming language in recent years. It supports both Object-Oriented Programming and functional programming. This article describes the features of JavaScript functional programming. Functional Programming Language

Functional programming languages are languages that are convenient to use the functional programming paradigm. Simply put, if you have the features required by functional programming, it can be called a functional language. In most cases, the programming style actually determines whether a program is functional.

What makes a language functional?

Function programming cannot be implemented in C language. Function programming cannot be implemented in Java (not including approximate function programming implemented through a large number of workarounds ). These languages do not contain structures that support functional programming. They are purely object-oriented and strictly non-functional languages.

At the same time, Pure Functional Languages cannot use object-oriented programming, such as Scheme, Haskell, and Lisp.

However, some languages support both modes. Python is a famous example, but there are other: Ruby, Julia, and Javascript we are most interested in. How can these languages support these two different design patterns? They contain the features required by the two programming paradigms. However, for Javascript, functional features seem to be hidden.

But in fact, functional languages need more than above. What are the features of functional languages?

Features Imperative Function Type
Programming style Perform the task step by step and manage the status changes Describe the problem and the required data changes to solve the problem
Status Change Important Does not exist
Execution sequence Important Not important
Main Control Flow Loop, condition, function call Function call and Recursion
Main Operation Unit Struct and Class Object Functions are the objects and datasets of first-class citizens.

The syntax of Functional Languages must take into account specific design patterns, such as type inference systems and anonymous functions. In general, this language must implement lambda calculus. In addition, the interpreter's evaluation policy must be non-strict and on-demand (also called delayed execution), which allows constant data structures and Non-strict and inert evaluation.

This section uses some specialized functional programming vocabulary. Lambda calculus is a formal system for function deduction (which sounds dizzy). It is required by internal and anonymous functions. Non-strict evaluation is similar to the inert evaluation, that is, not strictly calculating all elements according to the calculation rules, but Calculating only the useful part according to the final requirement, for example, if we want to take the first three items of an array with one hundred elements, the inert value is calculated as an array with only three elements, instead of calculating the array of the one hundred elements first.

Advantages

When you finally Master functional programming, it will give you great inspiration. Such experience will bring your programmer's career to a higher level, whether or not you will actually become a full-time functional programmer.

However, we are not discussing how to learn meditation. We are exploring how to learn a very useful tool that will make you a better programmer.

In general, what are the real advantages of functional programming?

More concise code

Function programming is simpler, simpler, and smaller. It simplifies debugging, testing, and maintenance.

For example, we need a function that converts a two-dimensional array into a one-dimensional array. If we only use imperative technology, we will write it as follows:

function merge2dArrayIntoOne(arrays) {  var count = arrays.length;  var merged = new Array(count);  var c = 0;  for (var i = 0; i < count; ++i) {   for (var j = 0, jlen = arrays[i].length; j < jlen; ++j) {    merged[c++] = arrays[i][j];   }  }  return merged}

Now, you can use the function technology as follows:

merge2dArrayIntoOne2 = (arrays) -> arrays.reduce (memo, item) ->  memo.concat item , []

var merge2dArrayIntoOne2 = function(arrays) { return arrays.reduce( function(p,n){  return p.concat(n); }, []);};

Note: the original code is incorrect. When the reduce function is called, the second parameter empty array is missing.

These two functions have the same input and return the same output, but the functional example is more concise.

Modular

Functional Programming forces large-scale problems to be split into smaller cases to solve the same problem, which means the code will be more modular. The modular program has a clearer description, easier debugging and easier maintenance. Testing will also become easier, because the code of each module can be checked separately.

Reusability

Due to its modular nature, functional programming has many common auxiliary functions. You will find that many functions can be reused in a large number of different applications.

In the subsequent sections, many of the most common functions will be covered. However, as a functional programmer, you will inevitably write your own function libraries, which will be used again and again. For example, a function is used to search for configuration files between lines. If it is designed, it can also be used to search for Hash tables.

Reduced Coupling

Coupling is a large number of dependencies between modules in a program. Functional Programming follows the compiling of pure high-level functions of first-class citizens, which makes them completely independent of global variables without any side effects and greatly reduces coupling. Of course, functions will inevitably depend on each other, but changing a function will not affect others, as long as the one-to-one ing between input and output is correct.

Mathematical correctness

The last point is more theoretical. Because it is rooted in lambda calculus, functional programming can prove correctness in mathematics. This is a huge advantage for some researchers who need to use programs to prove growth, time complexity, and mathematical correctness.

Let's take a look at the Fibonacci series. Although it is rarely used for issues other than proof of concept, it is very good to use it to explain this concept. The method to evaluate a Fibonacci series is to create a recursive function, like this:

fibonnaci(n) = fibonnaci(n-2) + fibonnaci(n–1) 

You also need to add a general situation:

return 1 when n < 2

This allows recursion to terminate and accumulates every step in the recursive call stack.

Detailed steps are listed below

var fibonacci = function(n) { if (n < 2) {  return 1;  }else {  return fibonacci(n - 2) + fibonacci(n - 1); } }console.log( fibonacci(8) );// Output: 34

However, with the help of a function library, an infinite sequence can be generated, which defines the members of the entire sequence through mathematical equations. Only the members we need will be computed.

var fibonacci2 = Lazy.generate(function() { var x = 1, y = 1; return function() {  var prev = x;  x = y;  y += prev;  return prev; }; }());console.log(fibonacci2.length());// Output: undefinedconsole.log(fibonacci2.take(12).toArray());// Output: [1, 1, 2, 3, 5,8, 13, 21, 34, 55, 89, 144]var fibonacci3 = Lazy.generate(function() { var x = 1, y = 1; return function() {  var prev = x;  x = y;  y += prev;  return prev; }; }());console.log(fibonacci3.take(9).reverse().first(1).toArray());//Output: [34]

The second example is obviously more mathematical. It depends on the Lazy. js function library. There are other such libraries, such as Sloth. js and wu. js, which will be discussed in chapter 3.

In the following example, the lazy execution just shows the mathematical correctness of functional programming. What's even more strange is that the author has to load and write the same internal function twice, which is meaningless ...... I think you should know that this is a lazy hold, so you don't have to go into it.

Functional Programming in the non-functional world

Can functional and non-functional programming be mixed together? Although this is the theme of chapter 7, we still need to understand some things before learning further.

This book does not want to teach you how to strictly use pure function Programming to Implement the entire application. Such applications are not suitable in academia. Instead, this book teaches you how to use a pure function design strategy on top of the necessary imperative code.

For example, you need to find the first four words containing only letters in a piece of text. Some immature writing methods will be like this:

var words = [], count = 0;text = myString.split(' ');for (i=0; count < 4, i < text.length; i++) { if (!text[i].match(/[0-9]/)) {  words = words.concat(text[i]);  count++; } }console.log(words);

Function programming is written as follows:

var words = [];var words = myString.split(' ').filter(function(x){ return (! x.match(/[1-9]+/));}).slice(0,4);console.log(words);

If there is a library of functional programming tools, the code can be further simplified:

The Code is as follows:


Var words = toSequence (myString). match (/[a-zA-Z] +/). first (4 );

The way to determine whether a function can be written into a more functional form is to find loops and temporary variables, such as the "words" and "count" variables in the preceding example. We can usually use higher-order functions to replace loops and temporary variables. The later part of this chapter will continue to explore them.

Is Javascript a functional programming language?

Now, we have another question: are Javascript functional languages or non-functional languages?

Javascript is the most popular but least understood functional programming language in the world. Javascript is a functional programming language dressed in C. Its syntax is undoubtedly similar to that of C, which means it uses the block Syntax of C language and the infix word order. And it is the worst name in an existing language. You don't have to imagine how many people will be confused by the relationship between Javascript and Java, just as its name implies what it will be! But in fact it has very little in common with Java. However, there are some ideas to force Javascript into object-oriented languages. libraries such as Dojo and idea. js have done a lot of work to abstract Javascript to make it suitable for object-oriented programming. Javascript came from the time when the world was clamoring for Object-Oriented in 1990s. We were told that Javascript was an object-oriented language because we wanted it to be like this, but in fact it was not.

Its real identity can be traced back to its prototype: Scheme and Lisp, two classic functional programming languages. Javascript has always been a functional programming language. Its function is a first-class citizen and can be nested. It has closures and composite functions that allow cool-chemistry and monad. All these are key to functional programming. There are also some reasons for Javascript being a functional language:

• The syntax of Javascript includes the ability to pass functions as parameters, a type inference system, and support for anonymous functions, high-level functions, and closures. These features are critical to the structure and behavior of functional programming.

• Javascript is not a pure object-oriented language. Most of its object-oriented design patterns are completed by copying Prototype objects. This is a weak object-oriented programming model. The European Computer Manufacturers Association script (ECMAScript)-formal form and standard implementation of Javascript-provides the following statement in version 4.2.1:
"Javascript does not have real classes like C ++, Smalltalk, and Java, but supports object constructors. In general, in a class-based object-oriented language, the state is carried by the instance, and the method is carried by the class. The inheritance is only for the structure and behavior. In EMACScript, the state and method are carried by the object, and the structure, behavior, and state are inherited ."

• Javascript is an interpreted language. Javascript interpreters (sometimes called "engines") are very similar to Scheme interpreters. They are all dynamic and all have flexible data types that are easy to combine and transmit. They both evaluate the Code as an expression block, and the method for processing functions is similar.

That is to say, Javascript is indeed not a pure functional language. It lacks inertia evaluation and built-in immutable data. This is because most interpreters call by name instead of by demand. Javascript is not very good at processing recursion because of its tail call. However, all these problems can be mitigated through some small considerations. A library named Lazy. js can be used to strictly evaluate infinite sequences and inertia values. A variable can only be implemented through programming skills. However, it is not restricted by dependency language, but requires the programmer's self-discipline. Tail recursion can be eliminated through a method called Trampolining. These questions will be explained in chapter 6.

There has been a lot of debate over whether Javascript is a functional language, object-oriented language, both of them, or both, and these arguments will continue.

Finally, functional programming uses clever changes, combinations, and functions to write concise code. In addition, Javascript provides a good way to achieve this. If you really want to explore the full potential of Javascript, you must learn how to use it as a functional language.

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.