Spring breeze in March
All the old iron in the point will be dVA sell meng blessing. I will combine theory with practice to explain how to use functional programming ideas to write high-quality functions. In this article, you can find a satisfactory answer.
Sometimes it’s not the answer that matters, it’s how you see and believe the answer.
After reading the theory paper, you can click on the following link to open the actual practice paper:
How to Write high-quality functions — Get through ren Du’s Two threads
This part was added after 10,000 words
Well, I was going to write one, but I’m running to 10,000 words. Although it has been more concise, but the knowledge involved is a bit more, or to spend the words to elaborate clearly. As a result, I decided to divide into two chapters to complete the chapter of rendu.
How to write this article
This is my third article in a series on writing high-quality functions — getting through the weeds.
The first two articles are:
How to write a high quality function – shock
How to write high-quality functions – named/commented/robust
The third article is an article on how to use functional programming to write high-quality functions.
I’ve been studying functional programming for a long time, and here I’d like to combine how to write high-quality functions with a feel that is different from other functional programming articles.
In line with the principle of not reinventing the wheel, but building a better wheel, I thought for a while before writing this article, and I found myself facing two questions. Here are the questions and answers:
The problems I face when I write articles
First question: How to describe functional programming in a high quality
The second question: how to improve the quality of writing functions by getting through the functional functions
My answer
The answer to the first question
I’m going to introduce functional programming by going through a few very detailed but very important pieces of functional programming, and show you how functional programming is a body of knowledge, and what it has in common and what it has in common with most of our bodies of knowledge today.
The answer to the second question
Here I will show you how to use functional programming to improve the quality of functions by analyzing code from open source projects and from my work and friends.
The above are some of the problems AND solutions I face. Finally, I wrote these two articles, hoping that they can be liked by everyone. Give me a “like” before you finish reading the article.
The Test of modern front-end engineers
Suddenly, let me unprepared, too late to think, will enter the new world.
Requirements are getting more and more complex
What I want to say is: due to the increasing complexity of front-end requirements, a large amount of business logic is put in the front end to realize, which relieves the pressure on the back end, but greatly increases the pressure on the front end. Front-end engineers have to complete a series of comprehensive operations such as storage, asynchronous, and events.
Requirements are becoming more demanding
We can look at a formula:
F (need) = perfect
Simply put: Input requirements, then output the best possible results.
As the complexity of requirements continues to increase, the fulfillment of requirements becomes more and more demanding, which will lead to a lot of pressure on front-end engineers. Not only do we have to address the various business scenarios we are responsible for, but we also have to ensure reducibility and development efficiency as well as online performance.
Common goals for front end engineers
I have summarized the following four points:
- Enhance development skills
- Improve code quality
- Improve development efficiency
- Enjoy life and
coding
The pleasure of
These four points sum up, and what we want to achieve is actually this picture:
All I can do is tell you what One Piece is in advance. Well, yes, that’s the picture above. Come on, guys.
The general state of the front-end engineer
But reality is a mixture of beauty and cruelty, and for a variety of reasons, the common reality of front-end engineers can be summarized as follows.
coder
的oop
Thinking is not strong, resulting in poor code qualitycoder
的fp
Thinking is not strong, resulting in poor code qualityJS
Problems with the language itself lead to poor code controllability
Why do I say that? Let me tell you
First of all, JS is a very flexible programming language. Under the dual effect of flexibility and weak foundation, the code will accumulate enough complexity, and the quality and controllability of the code will appear problems.
The following two sentences summarize the ideas of OOP and FP
Object-oriented programming makes code quality higher by encapsulating change.
Functional programming FP leads to higher code quality by minimizing changes.
Oop and FP ideas from front-end engineers are not very mature, and while the front-end world has been pushing to incorporate these ideas, it is still a problem.
My personal opinion and summary
I’m not saying that front-end engineers are bad, I’m just stating some objective points of view. You can think about why you don’t talk about PHP now, and it’s not because I love you.
We’re like a new generation of kids, and all we can do is take on the challenge. Even if at some point in the future, you do not do coder, but now, as a front-end coder, you should go to defeat it, not for anything else, just as a coder in the heart of a persistent and glory.
Popular Science – about programming languages
You come with me. I’ll go from fiction to science fiction.
Is JavaScript functional programming language
To answer this question, first, let’s be clear:
JS is not a pure functional programming language, so it is not a functional programming language.
Why is that?
Because it has an imperative language design like the for loop. True purely functional programming languages such as Haskell do not have for loops, and traversal operations use recursion.
The reason WHY I mention this point is because I want to make a point:
Since JavaScript is not pure functional programming language, it is not necessary for us to use JS, all using FP thought, we should do, should be to learn from each other. This is another way to end the discussion of functional programming in nuggets.
What language is JavaScript?
Here’s a quote:
Natural languages have no dominant paradigm, and neither does JavaScript. Developers can choose from a hodgepodge of procedural, functional, and object-oriented approaches and blend them as appropriate.
Said by: Angus Croll, “If Hemingway Wrote JavaScript”
Listen to me, although the above statement may be too absolute, if you want to know why the above statement is said, I recommend you to learn the principles of compilation.
Why am I suggesting this
It is because I personally believe that all high-level languages need to be translated into machine languages, and the lower the implementation, its ideas and methods are more specific and single. For example, lexical analysis, syntax analysis, industry methods are very few. It is also because standards can only be established if they are unified, like TCP/IP today.
Of course, it doesn’t make any sense for me to make this kind of nonsense, but we do know one thing for sure, and that is:
discussJavaScript
It doesn’t matter what language it’s based on.
What the hell is a first-class citizen anyway
JS functions are first-class citizen, that first-class citizen is what ghost oh? In fact, programming languages are divided into classes, roughly as follows:
First class citizens
If a value in a programming language can be passed as a parameter, returned from a program, and assigned to a variable, it is called a first-class citizen.
A second-class citizen
It can be passed as an argument, but cannot be returned from a subroutine or assigned to a variable.
Third-class citizens
Its value is not even passed as an argument.
JS functions are first-class citizens, so we can take the function as a parameter, can also be used as a return value, can also be assigned to variables. It is also because of first-class citizens, JS functional programming to shine.
The classification of functions
Don’t worry, dVA is now holding your hand, from the popular science studio to the cute studio.
Here are some of the things I’ve made up on a whim.
From the point of view of purity
- Pure functions
- The pure functions
Well, I have no one in this category, just like people, can be divided into people and not people…
Categorize in terms of call form
Infix function
The code is as follows:
6 * 6
Copy the code
The star in 6 times 6 is a function. And because it is in the middle of two expressions, it is called infix. Seeing this, you should have such thinking, that is when using these symbols in JS, it is natural to think of them as functions. You’ll find that the code becomes much easier to understand.
The prefix function
The code is as follows:
function f(str) {
console.log(str)
}
f('Hello, I am source terminator')
Copy the code
This execution of the function name f with an argument is called a prefixed function. I’m not going to talk about that, you should be familiar with it.
Mention the let
When I was studying Haskell, I discovered that Haskell also has lets. It was introduced like this:
let
This is followed by an expression that allows you to define local variables anywhere.
When I see this, I immediately think of JS let. This is consistent with the JS let, although other languages have lets as well, such as go. However, I am now more confident that the JS let was inspired by the Haskell LET.
So, in JS, I prefer to call lets bindings. In Haskell, let binding has a very limited scope. In JS, let binding has a very limited scope.
So you’ll find that using VAR makes perfect sense and sense in some scenarios.
I’m the dividing line, and the warm-up is over, and I’m about to start.
The overall idea of the article
When lost, again owned, will be more cherish it.
Well, let’s get down to business.
The first thing you can know is that the thinking of this article is clear. In the first half of the article, I will focus on the theoretical knowledge of functional programming. For example, I’ll address some of the confusion that many people have about functional programming. In the second half of this article, I will combine the source code of open source projects with coding in real work to show how functional programming can be used to write high-quality functions.
The following functional programming is collectively referred to as FP
The point about FP that you are really confused about –FP theoretical knowledge
As for theoretical knowledge, I will not cover all aspects of FP. I will try to take you to understand FP from a small point, so that you can have a clearer understanding of functional programming at the macro level.
Next, I’ll start with the following points:
- Why functional programming exists
- Declarative programming
- Function in mathematics
- Pure function/purity/idempotent/reference transparency /
- Side effects
- Immutability of data
- inert
- morphism
- High order
- Other theoretical knowledge
PS: I will not give a detailed introduction to a single point here, but just give my personal cognition and understanding of it.
Why functional programming exists
Here’s an explanation from a book:
The purpose of functional programming is to use functions to abstract the flow of control and operations acting on data, thereby eliminating side effects and reducing state changes in the system.
This sentence summary is very good, seems to be very profound, small friends do not be afraid, look at my analysis below you will understand.
If we take a look at the above explanation, we’ll see that this sentence actually means:
Functional programming is one way to solve problems.
Why DO I say this? Read on:
As we continue to analyze the above explanation, we can know the following two points:
First point: FP abstracts processes, such as control flows (such as for loops)
Second point: FP eliminates side effects in procedures (later)
A little derivation leads to the third point:
FP’s existence must be solved some of the pitfalls of other paradigms, such as some of the pitfalls of facing the object paradigm, in the face of objects is common, such as side effects from Java locking mechanism shows that the side effects of performance, of course I’m not ready to lock mechanism this view may, but must be solved the idea of some of the pitfalls of other paradigm, it is correct, Otherwise there would be no point in existence.
Mention the relationship between functional programming and abstraction
As mentioned in the first point above, FP abstracts the process, and as we know about abstractions, the lower the level of abstraction, the harder it is to reuse code and the more likely it is to make mistakes.
Why is it that the lower the level of abstraction, the harder it is to reuse code?
Let me give you an example so that you will understand. Just a word: Every time you eat a noodle, as a coder, you have two choices:
The first: go to the supermarket to buy noodles and eat them.
The second kind: mix noodles by yourself, roll noodles by yourself, and then eat them.
In fact, I have guessed that the abstract high and low is the difference between the first and the second. Think about it.
To sum up, we can know that:
That’s what FP is all about, and to really understand why it exists is to understand why we use functional programming.
A few days ago nuggets talk about FP
There was a lot of discussion about functional programming on the Nuggets, some saying functional programming is good, some saying it is not politically correct, some saying /^ refute /. Those days, every day I read the nuggets, I always wanted to say something, but in the end I didn’t say anything.
However, if you really understand what functional programming means, there won’t be so many different voices.
But the main reason for the noise is:
While writing an article, I would occasionally say absolute things, which would lead to other writers’ responses, and then the incident would continue to escalate, arousing the interest of the lovely melon-eating crowd and leading to a massive crowd of onlookers and discussion.
Here, I would like to end the controversy with one sentence, which is:
A function is not a tool, nor is itapi
It is a way to solve problems.
This sentence, do not explain, imagine for yourself.
Declarative programming
When we talk about declarative, we talk about imperative. Declarative and imperative are the two programming paradigms facing the front-end.
As you should know, functional programming is declarative programming. After reading my explanation of the meaning of FP above, you will understand why declarative programming exists.
FP
Control flow can be abstracted away from the program, which is declarative programming.
For programming paradigms, you can quickly browse the following wiki about programming paradigms:
[Wikipedia link – Programming Paradigm]zh.wikipedia.org/wiki/%E7%BC…
Question to consider: What is the weakness of declarative programming, and what is the essential difference between declarative programming and imperative programming? You can think about it.
Function in mathematics
Why? I think, if you want to better understand and use functional programming, you have to understand function in mathematics, because many of the concepts of functional programming are strongly related to the idea of function in mathematics.
Instead of analyzing it, I’ll post a wiki link:
Function – Wiki
And while you’re at it, you might want to scroll down to the bottom to see an introduction to category theory, the idea that category theory is really important for functional programming.
Pure function/purity/idempotent/referential transparency
These words are very common in FP, and in my opinion, the ultimate goal of these words is the same, that is, to achieve the purpose of FP mentioned above. Here’S a brief description of the ideas behind these words.
These words represent the same consciousness, which can be interpreted as:
Properties of pure functions include purity, idempotency, and referential transparency.
So what is a pure function? Pure functions can be recognized in the following way.
All functions return the same output for the same input.
PS: Of course, THIS article is not to let you use pure function to achieve programming, but want to let you use functional ideas to achieve programming, not necessarily pure function, pure function knowledge FP an idea.
Side effects of a function
The side effects of pure functions can be understood as follows:
The same input must produce the same output, and if it does not, it means that the function has side effects.
From this sentence, we can deduce that:
Because the output of I/O is indeterminate, all I/O has side effects.
How to deal with side effects
If you look at the dVA documentation or source code, all asynchronous requests are only done in effect, and effect is a functional programming concept with side effects in mind, which is a design concept that isolates the side effects of functions.
Immutability of data
It’s important to understand the immutability of data. I would like to ask a few questions:
First: the end of the immutability of the front-end data
Second: how does the front end achieve data immutability
Let’s answer both questions once and for all.
The front end appears for data immutability purposes
One other thing I want to say before I answer this question is that many programming languages support making data immutable, such as Final in Java, which is a great article to read. After watching it, you will have a cross understanding of immutable data.
Brief introduction to the final keyword in Java
Ok, personally, I think the idea of immutability is very simple, but very important, and I’ll give you an example to get the idea.
The code is as follows:
const obj = {}
const arr = []
const sum = 0
function main(arg){
// TODO:
}
main(obj)
main(arr)
main(sum)
Copy the code
From the code above, we know the following:
First point: Main’s arguments are external scope-dependent variables
Second point: The variable obj arr sum can be changed by the outside world
Third point: One thing to note is that we are currently unable to avoid external changes to these variables, which may have to be changed, or may be inadvertently changed.
Fourth: Although we can’t avoid the influence of the outside world, we can avoid the influence of ourselves. For example, if we use main to operate directly on obj and ARR itself, then obJ and ARR will be changed. If it is changed, then when we call main many times, There may be problems.
Fifth point: the code above violates the principle of functional programming, which is not to rely on external data, which can have side effects.
Based on the five answers above
Given the five points above, let’s think about how we can set arr obj sum to be an immutable data structure. Then we can directly avoid all influence from the outside world and ourselves. Because the data are immutable, the outside world can’t change them. So that’s why we have data immutability on the front end, because as the front end gets more complex, it becomes more obvious. Unfortunately, JS does not support immutable data structures.
How does the front end make the data immutable
There are three ways the front end can achieve data immutability:
The first method:
A new copy of the reference type is created within the function, and the specified business processing is performed on the copy.
The second method:
A common approach to encapsulating reference types in the industry is the value object pattern, which is exposed in the form of closures.
The third method:
JS API to achieve, with rules to prevent the modification of the object state. For example, using object.freeze () to freeze an Object causes a program error when the outside world tries to add, delete, or modify properties of the Object. For the third method, let’s take a look at the React source code and see where it is used, as shown here:
The nextProp object is frozen in reactdomComponent.js. It’s easy to see why.
First react assumes nextProp won’t change, so how can it be guaranteed that it won’t? Freeze (nextProp). React will know that the nextProp Object is immutable from this point on. So it can proceed to the next step, following immutability as a precondition. This also tells us that if we try to change it, we’ll get an error.
Immutability summary of data
It’s important to understand immutability. We can’t box immutability within a narrow range. For example, in the code above, the global variable sum is a value type. Therefore, immutability here is not immutability in a small range, but immutability in multiple levels, which needs more understanding and comprehension.
inert
I think inertia is not just a feature of FP, it’s also a very important idea in the front-end domain.
Inertia can be explained in one sentence:
It only happens when it’s needed.
To understand this sentence, let me enumerate the scenarios in which the lazy thought is used at the front. The scenarios are as follows:
- Lazy loading of the front end
- The front end
tree shaking
- Infinite list problem
recycle list
- Dynamic Import/Export
- Front-end cache
If you think about it, the lazy purpose of FP is already contained in those scenarios.
About only happening when you need to. This sentence, small partners can be combined with my list of scenes for comparison and understanding, I will not continue to explain pale, point to the end.
morphism
The reason I say this is because understanding morphisms is very important for you to use functional programming better.
So what is morphism?
Simply understood, it is a mapping from one state to another. There are many forms of morphism, so let’s talk about type mapping. For example, if you type a String and then return a Boolean, this is a morphism.
For example, the following demo:
const isNumber = n= > typeof n === 'number'
Copy the code
The above function, which inputs numbers and inputs booleans, is a morphism form. Many of the concepts of functional programming are related to morphism, such as pipelining, higher-order, composition, and chain. How to map one type of data organization into another type of data structure is a very important knowledge point. Here I put forward the core points, and you must understand and master them more.
High order
High order is one of the core ideas of functional programming, which must be realized by high order in higher abstraction. Instead of a traditional loop structure filled with temporary variables and side effects, you reduce the amount of code to maintain and potentially go wrong by taking functions as parameters and injecting specific behavior into the current function to solve specific tasks.
I think high order is a very important property, and if you want to play functional programming, you have to play high order. for
Why do I say that?
Because as you can see, the pipelining, the composition, the Currization of functions, all depend on the higher order of functions. A higher-order function, let’s call it a higher-order function, so what is a higher-order function?
The definition of HOC(higher-order -Functions) as I understand it at present is as follows:
If you pass in a function as an argument and return a function as a result, you can call a function of higher order if you have one of these two conditions.
About higher-order functions, more is to understand and actual combat, here on the theory of knowledge I do not introduce, we combined with my actual combat to understand.
Other theoretical knowledge
The theoretical knowledge I’ve mentioned above, all of which are atomic-scale properties, are the building blocks of FP. Other higher-order implementations, such as Currization, partial applications, function composition, functors, etc., build on these previous cornerstones. Therefore, I will not introduce them in this theoretical article. You can analyze and learn by yourself. I will string together these advanced implementations in the practical part. Of course, if you are interested in this theoretical knowledge of small partners, want to communicate with me, you can also talk about me privately.
Summary of FP theoretical knowledge
FP is a great thing, it helps you control the complexity of your code, it enhances your logic, it makes testing easier, and so on.
Now, compare the following two questions:
- Are learning algorithms useful to front-end engineers
- Is learning functional programming useful to front-end engineers
You’ll see that they’re all useful, but that doesn’t mean we should use them a lot in real front-end scenarios.
I think the front-end needs to master the level of FP
Above, I have introduced some meta-knowledge that I think we need to master in the field of FP. Only by mastering these meta-knowledge can we better and faster grasp the realization of various functions derived from meta-knowledge. Such as Coriolization functions, partial application functions, combinatorial functions, higher-order functions and even functors.
But in fact, after I practiced FP, I personally think that front-end engineers now in FP, just need to mix, curry, and high order play well on the line. Other advanced uses can be left out of practice. I think the front end engineer will be able to take functional thinking to the extreme in the front end by mastering these three. This is the understanding of LEARNING FP.
At the end of the article to summarize
I wanted to write one, but I found one was too long, so I split it into two parts.
Functional programming, involves a lot of things, light theoretical knowledge is a lot of, my article for theoretical knowledge, not too much to explain and analysis, I am in accordance with my personal understanding and summary to show you how to solve the theoretical knowledge of functional programming. Therefore, there may be some opinions are not unified, or the theoretical knowledge is not complete, please understand and support more. This article is not just about how to do FP, but about how to write high quality functions.
reference
Refer to the link
- The illustration Monad
- monad wiki
- What is a monad? -stackoverflow
- Reading Notes: Category theory
Reference books
- JavaScript ES6 functional programming primer classic
- A guide to JavaScript functional programming
- Haskell’s Guide to Fun Learning
- Other E-books
communication
The article series on how to write high-quality functions is as follows (not included in this article) :
- How to write a high quality function – shock
- How to write high-quality functions – named/commented/robust
Follow my Nuggets blog or Github for updates on the upcoming series. Nuggets series of technical articles summarized below, if you feel good, click a star to encourage it.
github.com/godkun/blog
I am the source terminator, welcome technical exchange.
Also can go toFront end rhapsody groupBrainstorm together. Have want to add, because the person is full, can add my good friend first, I will invite you into the group.
The language of the wind
Finally: respect the original, reprint please indicate the source ha 😋