Hello, everyone, this is Yi Jun @ Monday commuter radio channel. This channel will start from a knowledge point, so that your commute will not be boring or tired.
This article is about 1250 words in total, and the reading time is about the same as Tao Zhen's beach.
1. Definitions
Functional programming means creating the best results of clean and maintainable software. It is a programming paradigm.
It is not opposite to object-oriented programming (OOP) and process oriented programming (OPP). It is usually discussed together with declarative programming and imperative programming.
2. Features
2.1 the function is first class
In fact, the so-called first-class citizen functions are the same as other data types. You can insert them into an array, use them as parameters, and assign them to variables.
When you write let myFun = function() {}, you just take a function as data.
Let's look at the following example:
var print = function(i){ console.log(i); }; [1,2,3].forEach(print);
The print variable is a function, but can be used as an argument to the forEach function.
2.2 pure function
The ideal of functional programming is the so-called pure function.
When the inputs are the same, the output of the pure function remains unchanged and will not produce any side effects.
- Output unchanged
// pure var checkNum = function(num) { var minimum = 21; return num >= minimum; }; // Impure var minimum = 21; var checkNum = function(num) { return num >= minimum; };
In the impure version, the return value of the function depends on the external element of minimum, which is not invariant.
For another example, slice and splice functions. Slice conforms to the definition of a pure function because it guarantees the same output for the same input. But splice can't.
var array = [1,2,3,4,5]; array.slice(0,3);// [1,2,3] array.slice(0,3);// [1,2,3] array.splice(0,3);// [1,2,3] array.splice(0,3);// [4,5]
- side effect
Any interaction with the external environment of the function is a side effect.
Common examples:
- Database insert
- Print / log
- Change file system / read file
- Access system status
Side effects make pure functions impure because functions need to deal with the outside world. If your program is mostly composed of pure functions, the testing and debugging of the program will be very convenient.
In OOP, object methods are designed to interact with object states (object members). In contrast to OPP code, external states are often operated from functions.
However, in practice, functions often end up interacting with a broader context.
3. curry, one of the tools
Coriolised logic: only pass part of the parameters to the function to call it, and let it return a function to process the remaining parameters.
A simple example:
// Before Coriolis function add(x, y) { return x + y; } add(1, 2) // 3
// After coritization function add(y) { return function (x) { return x + y; }; } //Or use the arrow function //const add = x => y => x + y; add(1)(2) // 3
Here we define an add function that takes a parameter and returns a new function.
After calling add, the returned function remembers the first parameter of add through the closure method.
Of course, we can use the curry helper function to make it easier to define and call such functions.
4. Examples of functional programming in Java
Perhaps the most prominent example of functional programming is in dealing with collections. This is because the ability to apply large blocks of functions to items in a set naturally coincides with the idea of pure functions.
- Using map() and an anonymous function in Java
import java.util.*; import java.util.stream.Collectors; import static java.util.stream.Collectors.toList; //... List lower = Arrays.asList("a","b","c"); System.out.println(lower.stream().map(s -> s.toUpperCase()).collect(toList()));
This clean and concise Java code realizes the function of capitalization of letters in an array, and creates a function that accepts parameters, executes logic and returns values.
The advantage of this syntax is that the code is tightly centralized. Operations such as loops and arrays are not required.
It is worth noting that if there are no braces around the body of the function so defined, the return value will be given automatically.
- Java double colon operator
// ... List upper = lower.stream().map(String::toUpperCase).collect(toList());
In this example, we did the same thing as example 1. Different grammars can come in handy in different situations.
In the above two examples, you can see that higher-order functions work. The map() function in both languages accepts a function as an argument.
Thank you for watching this episode of Yi Jun @ Monday commuter radio. If you think it's good, give me three company support. We'll see you next time.