JavaScript functional programming language _javascript skills

Source: Internet
Author: User
Tags data structures prev

Functional programming languages

Functional programming languages are those that facilitate the use of functional programming paradigms. In short, if you have the features you need for functional programming, it can be called a functional language. In most cases, the style of programming actually determines whether a program is functional.

What makes a language a functional feature?

Functional programming cannot be implemented in C language. Functional programming also cannot be implemented in Java (excluding those approximate functional programming that is implemented by a large number of workarounds). These languages do not contain structures that support functional programming. They are purely object-oriented, strictly non functional languages.

Also, pure functional languages cannot use object-oriented programming, such as scheme, Haskell, and Lisp.

However, some languages are supported by both modes. Python is a famous example, but there's something else: Ruby,julia, and the JavaScript we're most interested in. How do these languages support the design patterns that are so different from each other? They contain the characteristics required by both programming paradigms. However, for JavaScript, functional features seem to be hidden.

But in fact, functional languages need more than that. What is the characteristic of functional languages?

features command- function Type
Programming style Perform step-by-step and manage changes in state Describe the problem and the required data changes to solve the problem
State change is important does not exist
Order of execution is important It's not important.
The main control flow loops, conditions, function calls function calls and recursion
Main unit of Operation Structure body and class object function as a first-class citizen's object and dataset

The syntax of a functional language must take into account specific design patterns, such as type inference systems and anonymous functions. In general, the language must implement the lambda calculus. And the interpreter's evaluation strategy must be strictly, on demand (also called deferred execution), which allows invariant data structures and non rigorous, lazy evaluation.

This section uses some functional programming terminology. The lambda calculus is a formal system of function deduction (sounds faint), and its prerequisites are internal functions and anonymous functions. Non-rigorous evaluation and lazy evaluation almost one meaning, is not strictly according to the rules of the calculation of all the elements first, but based on the final need to calculate only the useful part, such as we want to take 100 elements of the first three of the array, the lazy evaluation will actually calculate a three element is an array, Instead of counting the 100-element array first. 

Advantages

When you finally mastered the functional programming it will give you great inspiration. This experience will make your programmer's career a step behind, whether you really become a full-time functional programmer or not.

But we are not discussing how to meditate now; we are exploring how to learn a very useful tool that will make you a better programmer.

In general, what are the real benefits of using functional programming?

More Concise Code

Functional 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 use only imperative techniques, we'll write this:

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++] = AR RAYS[I][J];
   }
  Return merged
}

Now using functional techniques, you can write this:

Merge2darrayintoone2 = (arrays)->
 arrays.reduce (Memo, item)->
  memo.concat item
 , []
var merge2darrayintoone2 = function (arrays) {return
 arrays.reduce (function (p,n) {return
  p.concat (n);
 }, []);
};

In the original, the code is wrong, the reduce function is called less than the second empty array of parameters, which has been filled.

The two functions have the same input and return the same output, but the example of the function is more concise.

of modular

Functional programming forces large problems to be split into smaller cases that solve the same problem, which means that the code is more modular. Modular programs have a clearer description, easier to debug, and simpler to maintain. The test will also become easier because each module's code can be tested separately for correctness.

Reuse of

Because of its modular nature, functional programming can have many common auxiliary functions. You will find that many of the functions in this area can be reused in a number of different applications.

In later chapters, many of the most common functions will be overwritten. However, as a functional programmer, you will inevitably write your own library of functions that will be used again and again. For example, a function that looks up a configuration file between the rows, and can be used to find a hash table if it is well designed.

Reduce coupling

Coupling is a large number of dependencies between modules in a program. Because functional programming follows higher-order pure functions that write first-class citizens, they have no side effects on global variables and are completely independent of each other, and the coupling is greatly reduced. Of course, functions will inevitably depend on each other, but changing a function does not affect others, as long as the one-to-one mapping of input and output remains correct.

Mathematical correctness

The last point is more theoretical. Because it is rooted in the lambda calculus, functional programming can be mathematically proven to be correct. This is a huge advantage for some researchers who need to use procedures to demonstrate growth rates, time complexity and mathematical correctness.

Let's take a look at the Fibonacci sequence. Although it is rarely used for questions other than conceptual proofs, it is very good to use it to explain this concept. The way to evaluate a Fibonacci sequence is to create a recursive function, like this:

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

You also need to add a general scenario:

Return 1 when n < 2

This allows recursion to terminate and allow each step in the recursive call stack to accumulate from here.

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 aid of a lazy executive function library, an infinite sequence can be generated, which defines the entire sequence of members through mathematical equations. Only those members that we ultimately need will be counted at last.

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:undefined
Console.log (Fibonacci2.take) (ToArray ());
Output: [1, 1, 2, 3, 5,8, 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 (). A (1). ToArray ());
Output: [34]

The second example clearly has a more mathematical flavour. It relies on the Lazy.js function library. There are other such libraries, such as Sloth.js, Wu.js, which will be mentioned in chapter Iii.

I insert a few words: the lazy execution of the following example put this seems to be just to show the performance of functional programming in mathematical correctness. Even more surprising is that the author also has the same internal function of lazy loading two times, completely meaningless ah ... I think you reader know this is a lazy hold on the line, do not have to delve into.

Functional programming in a non-functional world

Can functional and non-functional programming be mixed together? Although this is the theme of the seventh chapter, before we go any further, we need to figure something out.

This book does not want to teach you how to strictly use pure function programming to achieve the entire application. Such applications are not appropriate outside the academic world. Instead, this book teaches you how to use pure function design strategies on top of imperative code.

For example, you need to find the first four words that contain only letters in a paragraph of text:

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);

Functional programming can be written like this:

var words = [];
var words = Mystring.split ('). Filter (function (x) {return
 (! X.match (/[1-9]+/));
}). Slice (0,4);
Console.log (words);

If you have a tool library for functional programming, your code can be further simplified:

Copy Code code as follows:

var words = ToSequence (myString). Match (/[a-za-z]+/). (4);

The way to judge whether a function can be written in more functional form is to look for loops and temporary variables, such as the "Words" and "count" variables in the previous example. We can usually replace loops and temporary variables with higher-order functions, and we'll continue to explore them later in this chapter.

is JavaScript a functional programming language?

Now there's one last question. We need to ask ourselves, is JavaScript a functional language or a non functional language?

JavaScript can be said to be the most popular but least understood functional programming language in the world. JavaScript is a functional programming language that wears a C-coat. Its syntax is undoubtedly similar to C, which means it uses the block grammar of C language and the infix word order. And it's the worst name in the existing language. You don't have to imagine how many people will be confused by JavaScript and Java relationships, as if their name implied what it would be! But in fact it has very little in common with Java. But there are some ideas to force JavaScript into object-oriented languages, such as Dojo, Ease.js, which have done a lot of work trying to abstract JavaScript to fit object-oriented programming. JavaScript came from the 90 's when the world was screaming about object-oriented times, and we were told that JavaScript is an object-oriented language because we want it to be like this, but it's actually not.

Its true 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 it can be nested, it has closures and composite functions, it allows for the physical and monad of Cosette. All of this is the key to functional programming. Here are some other reasons why JavaScript is a functional language:

The lexical features of JavaScript include the ability to transfer functions as parameters, have type inference systems, support anonymous functions, high-order functions, closures, and so on. These features are critical to the structure and behavior of the constituent functional programming.

JavaScript is not a pure object-oriented language, and most object-oriented design patterns are done by copying prototype objects, which is a weak object-oriented programming model. European Computer Manufacturers Association script (ECMAScript)--javascript formal form and standard implementation--in the 4.2.1 version of the specification has the following statement:
"JavaScript does not have a real class like C + +, Smalltalk, Java, but it supports the constructor that creates the object." In general, in a class-oriented object-oriented language, states are hosted by instances, methods are hosted by classes, and inheritance is only for structure and behavior. In Emacscript, states and methods are hosted by objects, and structures, behaviors, and states are inherited. ”

JavaScript is an interpretive language. The JavaScript interpreter (sometimes called the "engine") is very similar to the scheme's interpreter. They are dynamic, have flexible data types that are easy to combine and transmit, and evaluate the code as an expression block, as well as a way to handle functions.

In other words, JavaScript is really not a pure functional language. It lacks inert evaluation and built-in immutable data. This is because most interpreters are called by name rather than on demand. JavaScript is also less adept at handling recursion because of the way its tail calls are handled. But all of these problems can be mitigated by minor caveats. Non-rigorous evaluation that requires infinite sequences and lazy evaluation can be achieved by a library called Lazy.js. Invariants can only be achieved by simple programming techniques, but they are not limited by the language level but require self-discipline on the programmer. Tail-recursive elimination can be achieved by means of a method called trampolining. These questions will be explained in the sixth chapter.

There has always been a lot of debate about whether JavaScript is a functional language or an object-oriented language, or both, and these arguments have to go on.

Finally, functional programming is the way to write concise code by subtly changing, combining, and using functions. And JavaScript provides a good way to achieve these. If you really want to tap into the full potential of JavaScript, you have to 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.