Definition
" Functional programming; It is a type of" Programming Paradigm; (Programming paragraph), which is the methodology of how to write a program.
It belongs to" Structured programming; One of the main ideas is to write the operation process as a series of nested function calls as much as possible. For example, there is now a mathematical expression:
(1 + 2) * 3 - 4
Traditional procedural programming may be written as follows:
var a = 1 + 2; var b = a * 3; var c = b - 4;
Functional programming requires the use of functions. We can define the operation process as different functions and write them as follows:
var result = subtract(multiply(add(1,2), 3), 4);
Other programming paradigms include object-oriented programming, logical programming, and so on.
Advantages
The significance of programming paradigms lies in their provision of various ideas and methods for modular code. Functional programming is no exception.
- Simple code and fast development
- Approaching natural language, easy to understand
- More convenient code management
- Easy" Concurrent programming;
- Provide hot updates for code
Functional programming is a set of programming methods that organize modules with functions as the core.
The function is "first-class citizen" .
It refers to the equal status of functions and other data types, which can be assigned to variables, passed as parameters to another function, or used as the return value of another function.
It is a prerequisite for the implementation of functional programming, as our basic operations involve manipulating functions. This feature means that functions, like other data types, are on an equal footing and can be assigned to other variables, used as parameters, passed into another function, or used as the return value of another function. Callback functions are a typical application.
Stateless and data immutable .
This is the core concept of functional programming:
- Data immutability: It requires all your data to be immutable, which means that if you want to modify an object, you should create a new object to modify it, rather than modifying existing objects.
- Stateless: It mainly emphasizes that for a function, no matter when you run it, it should be given the same input and output as the first run, completely independent of external state changes.
High-order function .
A high-order function takes one or more functions as parameters and returns a new function. If one of the two conditions is met, it is a high-order function, which is used to modify the parameters of the function or control the execution process and return result of the function; Common high-order functions include curry, compose, and some methods for arrays such as map and find;
function add(a, b){
return a + b
}
// HOF
function HOF(fun){
return function(...args){
return args[0] - args[1]
}
}
var transformAdd = HOF(add);
console.log(transformAdd(5, 2)) // 3
The above functions have been wrapped by higher-order function HOF, which forcibly changes the execution mode and results of the functions; High priced functions can be used to encapsulate the unified function mixin, allowing for finer grained control of functions and better realization of the "single responsibility" concept of functions;
Pure function .
A pure function refers to a function that satisfies both of the following conditions:
- The result of a function depends only on the input parameters and is independent of the external system state - as long as the input is the same, the return value is always unchanged.
- Do not modify the external state of the program (such as global variables and input parameters) except for the return value- Meeting this condition is also known as "no side effects" (Side effects refer to the interaction between the internal and external of a function, producing results other than operations. For example, during a function call, if an external variable is used and modified, it is a function with side effects.)
Pure functions are relatively independent program components. Because the result of a function only depends on the input parameters and is independent of the external system state, unit testing and debugging become exceptionally easy, which is also one of the advantages of modularity.
Referencing Transparency .
It refers to the fact that the operation of a function does not depend on external variables or" Status;, Relying solely on input parameters, as long as the parameters are the same, the return value obtained by referencing the function is always the same.
Lazy execution .
It refers to the function being executed only when needed, without generating meaningless intermediate variables. The biggest difference between functional programming and imperative programming is that there are almost no intermediate variables. It writes functions from beginning to end and only produces actual results at the end.
Coriolization and function combination
currying .
It refers to converting a multivariate function into a sequentially called unit function.
F (a, b, c) → f (a) (b) (c).
For example:
const add = (x) => { return (y, z) => { return x + y + z } }
let increase = add(1); console.log(increase(2, 3)); // 6
Coriolization application .
In practice, the use of Coriolization is to make a function singular, which can increase the diversity of the function and make its applicability stronger:
const replace = curry((a, b, str) => str.replace(a, b));
const replaceSpaceWith = replace(/s*/);
const replaceSpaceWithComma = replaceSpaceWith(',');
const replaceSpaceWithDash = replaceSpaceWith('-');
Through the above method, we can generate many new functions from a replace function that can be used in various situations.
Single valued functions are the foundation of the combination of functions that we will soon discuss.
Function combination .
It refers to passing several function objects as parameters to a function, and nesting the incoming function parameters as parameters inside the function.
For example:
const compose = (f, g) => x => f(g(x))
const f = x => x + 1; const g = x => x * 2;
const fg = compose(f, g); fg(1) //3
We can see that composite implements a simple function: it forms a brand new function, which is a function that starts from g -> The assembly line of f. At the same time, we can easily find that composite actually satisfies the associative law.
compose(f, compose(g, t)) = compose(compose(f, g), t) = f(g(t(x)))
As long as their order is consistent, the final result is consistent. Therefore, we can write a more advanced composite that supports multiple function combinations:
compose(f, g, t) => x => f(g(t(x))
Function Combination Application .
Consider a small feature: capitalize the last element of an array, assuming that the log, head, reverse, toUpperCase functions exist.
const upperLastItem = compose(log, toUpperCase, head, reverse);
Through the parameters, we can clearly see what UpperLastItem did. It completed a set of pipelines, and all parameters that passed through this pipeline will go through: reverse -> Head -> ToUpperCase -> The processing of these functions, such as log, generates the final result.
Does object-oriented and functional programming conflict
Object orientation has always been in the paradigm of what data I can manipulate and how I should manipulate that data. Functional programming has always been immersed in the methods of manipulating data for me. The biggest advantages of object-oriented programming are polymorphism and encapsulation; The advantages of functional programming are abstraction and declarative command styles, which are actually orthogonal, complementary, and can coexist in the same program. Debating whether object-oriented or function oriented is good is just as extreme as debating which language is good. For object-oriented programming, not all that exists is objects, functions are objects; For functional programming: what exists is not always pure, and side effects are always real. In short, object-oriented programming focuses on decomposition, while functional programming focuses on composition.
Summary
- Functional programming revolves around high-order functions, and the core of design lies in the design of high-order functions.
- Functional programming focuses on data mapping, while imperative programming focuses on problem-solving steps
- In addition to pure functional programming languages, functional programming methods can also be established in non functional programming languages.