Programming language commonality------What is functional programming?

Source: Internet
Author: User

After more than 50 years of birth, functional programming (functional programming) began to gain more and more attention.

Not only did the oldest functional language Lisp regain their youth, but new functional languages such as Erlang, Clojure, Scala, F #, and so on were emerging. Currently the most popular Python, Ruby, Javascript support for functional programming is strong, even the old-style object-oriented Java, process-oriented PHP, are scurried to add to the anonymous function support. There are more and more indications that functional programming is no longer the favorite of academia, and it is starting to be practical in the industry.

Perhaps after "object-oriented Programming", "functional programming" becomes the dominant paradigm of the next programming (paradigm). The programmers of the future will probably have to understand a bit more or less.

However,"functional programming" seems to be difficult, lack of popular introductory tutorials, various introduction articles are filled with mathematical symbols and special terms, let people read such as falling clouds. Even the most basic question, "What is functional programming", can not be easily understood on the Internet.

Here is my "functional programming" study notes, shared, and discussed with you. The content does not involve mathematics (Lambda calculus I do not understand), nor does it involve advanced features (such as lazy evaluation and currying), but simply as simple as possible to organize and express, I now understand the "functional programming" and its significance.

I mainly refer to Slava Akhmechet's "functional programming for the Rest of Us".

First, the definition

Simply put, "functional programming" is a "programming paradigm" (programming paradigm), which is how to write a program's methodology.

It belongs to "structured programming", the main idea is to write the operation process as far as possible as a series of nested function calls. For example, there is now a mathematical expression:

(1 + 2) * 3-4

Traditional procedural programming, which may be written like this:

var a = 1 + 2;

var B = A * 3;

var c = b-4;

Functional programming requires the use of functions, which can be defined as different functions, and then written as follows:

var result = Subtract (multiply (add), 3), 4);

This is functional programming.

Second, the characteristics

Functional programming has five distinct characteristics.

1. function is "first Class citizen"

The so-called "first class citizen", refers to the function and other data types, equal status, can be assigned to other variables (var result = Subtract (multiply (add), 3), 4);), can also be used as parameters, Pass in another function, or as a return value for another function.

For example, the print variable in the following code is a function that can be used as an argument to another function.

var print = function (i) {console.log (i);};

[1,2,3].foreach (print); Print as function

2. Use "expression" only, without "statement" ()

Expression is a simple arithmetic process, always has a return value;

"Statement" (statement) is to perform some action (more logical statements.) ), there is no return value.

Functional programming requires that only expressions be used and no statements are used. In other words, each step is a simple operation, and there are return values.

The reason is that the development motive of functional programming is to deal with the operation (computation), regardless of the system's read-write (I/O). "Statement" is a read and write operation to the system, so it is excluded.

Of course, in practical applications, it is not possible to do I/O. Therefore, in the programming process, functional programming only requires to limit the I/O to the minimum, do not have unnecessary read and write behavior, maintain the simplicity of the computational process.

3. There is no "side effect" (single duty, one thing to do, avoid coupling association.) )

The so-called "side effect" (side effect), refers to the function inside and outside interaction (the most typical case is to modify the value of the global variable), resulting in other results than the operation.

Functional programming emphasizes that there is no "side effect", meaning that the function is to remain independent, all functions are to return a new value, no other behavior, especially the value of the external variable must not be modified.

4. Do not modify the status

As mentioned above, functional programming simply returns the new value without modifying the system variable. Therefore, not modifying the variable is also an important feature of it.

In other types of languages, variables are often used to hold "state". The variable is not modified, which means that the state cannot be saved in the variable. Functional programming uses parameters to save state, and the best example is recursion. The following code is a function that arranges strings in reverse order, demonstrating how different parameters determine the "state" in which the operation is located.

function reverse (string) {

if (String.Length = = 0) {

return string;

} else {

return reverse (string.substring (1, string.length)) + string.substring (0, 1);

}

}

Due to the use of recursion, functional language is slow to run, this is its long-term can not be promoted in the industry the main reason.

5. Referencing transparency

Reference transparency (referential 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 reference function will always get the same return value.

With the 3rd and 4th in the front, this is obvious. In other types of languages, the return value of a function is often related to the system state, and the return value is not the same in different states. This is called "citation opaque" and is detrimental to observing and understanding the behavior of the program.

Third, significance

What are the benefits of functional programming and why is it becoming more and more popular?

1. Simple code, rapid development

Functional programming uses a large number of functions, reducing the duplication of code, so the program is relatively short and development speed is faster.

Paul Graham wrote in the book "Hackers and Painters": the same function of the program, in extreme cases, the length of the Lisp code may be one-twentieth of the C code.

If the code lines written by programmers are basically the same every day, it means that "C requires a year to complete the development of a feature, and the Lisp language only takes less than three weeks." Conversely, if a new feature, Lisp language completed development takes three months, C language needs to write five years. "Of course, such comparisons deliberately exaggerate the difference, but" in a highly competitive market, even if the pace of development is only two or three times times the difference, it is enough to keep you in a backward position forever. "

2. Close to natural language, easy to understand

Functional programming has a high degree of freedom to write code that is close to natural language.

The previous article used the expression (1 + 2) * 3-4 as a functional language:

Subtract (multiply (add), 3), 4)

To deform it, it is not difficult to get another way of writing:

Add. Multiply (3). Subtract (4)

This is basically the expression of natural language. Look at the following code, you should be able to understand its meaning at a glance:

Merge ([1,2],[3,4]). Sort (). Search ("2")

As a result, the code for functional programming is easier to understand.

3. More convenient code management

Functional programming is not dependent, and does not change the state of the outside world, as long as the input parameters are given, the returned result must be the same. Therefore, each function can be considered as a standalone unit, which is advantageous for unit tests (unit testing) and debugging (debugging), as well as modular combinations.

4. Easy "Concurrent Programming"

Functional programming does not need to consider "deadlock" (deadlock), because it does not modify variables, so there is no "lock" thread problem. Instead of worrying about a thread's data being modified by another thread, you can confidently spread the work across multiple threads and deploy concurrent programming (concurrency).

Take a look at the following code:

var S1 = Op1 ();

var s2 = Op2 ();

var s3 = concat (S1, S2);

Since S1 and S2 do not interfere with each other, the variables will not be modified, and whoever executes first is irrelevant, so you can safely increase the threads and assign them to two threads to complete. Other types of languages do not do this because S1 may modify the state of the system, and S2 may use these states, so it is important to ensure that S2 runs after S1 and naturally cannot be deployed to other threads.

Multi-core CPUs are the future trend, so this feature of functional programming is very important.

5. Hot Upgrade of code

Functional programming has no side effects, as long as the interface is not changed, the internal implementation is externally irrelevant. Therefore, you can upgrade the code directly in the running state without requiring a restart or downtime. The Erlang language has long proven this, it was developed by Swedish Ericsson in order to manage the telephone system, and the upgrade of the telephone system is of course no downtime.

Https://www.cnblogs.com/feichengwulai/archive/2014/03/29/3632219.html

Programming language commonality------What is 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.