Learn to program What is a monad

Everything starts with the dialogue with Jun Xiaotian

Earlier about the advantages of functional programming. For example, functions can be used as variables and then an attempt can be made to avoid writing side effect programs.
After that, it can be said that I came across a super difficult thing monad.

When I wrote Java it was probably the following code

Then you don't know the difference between a map and a flatmap. For a lazy programmer, of course, the answer is not to ask Google, but to bring in a colleague.
I: "Oda, what's the difference between flat and flatmap?"
Oda: "Ah, that's a monad"
I: "Monado?"
Oda: "Well, Monad"
I: "What is Monado?"
Oda: "This is related to the category theory"
I: "What is the category theory of (tmd)?"
Oda: "I don't really understand category theory, but I think map and flatmap can be clearly explained."
I: "Ah, can you tell me about it this way? (Why did you say something about category theory? Does it seem like you are exaggerating?)"
After that, Oda talked to me about the difference between the two for about 10 minutes. I basically said "Ah ~", "Oh!", "Oh?" . At that time, I felt I got it, and then after two days I forgot. Now I think he probably said it wrong! ! !
When Oda-kun taught me this knowledge, I really didn't feel on the same level as him and suddenly felt very out of date, so I had to fill in the knowledge quickly.
So I actually googled the monad. Then Wikipedia took a look at it and saw something similar.

Anyway, I have a feeling that this is not human language.
So I asked Du Niang and then read some articles. Some thoughts like "list" appeared. It may be that the influence of object-oriented thinking is too deep and your patience is too poor to understand its content. So I wondered if I should learn a functional language.
So I read "Functional Programming in Javascript". Since js is basically still writing, the cost of learning is relatively low. The book is expected to have a special chapter on monads, but after a while when I saw the chapter on monads, some of my understanding of monads disappeared through the survey before they basically went away. Can understand monad.
So I furiously opened YouTube and looked for Monad! Then a video of this old man appeared.

This old man named Brian Beckham explained the monad very briefly (at least when I saw the video) without using any math specific vocabulary and then I honestly didn't get it ...
So I finally made up my mind to learn Haskell. I think it may be easier to understand monads in this language. Although the concept of the monad certainly does not depend on any language. But language can actually help you understand because you are actually thinking in language.
Haskell later found that Brian Beckham's explanation was easy to understand, but his good thing was that "what is this but it's amazing nonetheless".
My current thinking about functional programming is not as deep in the bone as it is object-oriented. It may be better to use the "pre-functional programming era" mind. Probably a lot of people who weren't familiar with functional programming understand that monad is going to be a waste. Try not to use functional buzzwords and explain the monad.

There are two types of sayings on the internet: The nouns I am thinking of are not exact terms.
container theory
Chain theory
Briefly explain the two of them

Container theory

A monad is like a container, and a value is stored in the container.
The picture stolen from a foreign website is a very descriptive description.

2 This number is placed in a container.
You may first ask why we need a container. I'll talk about it later ...
Although the container stores the number 2, the container itself cannot perform ordinary math operations like +3 directly. Container ([2]) and 3 are not a type.
What should I do if I want to calculate 2 in the container? Then take 2 out of the container (picture), but after the calculation is done you will need to put them back into a container (not the container used before 2) or repackage them.
But do we have to take 2 out of the container for calculation and repackage? What does that mean? At least that's what I thought when I first saw it. Leads only to chain theory

Chain theory

An earlier article stated that functions in a functional language can be passed as variables and can also be combined. When you combine functions, your processing can be linked like a chain.
Write another pseudocode
Assuming a-> a, this means a function. It takes a parameter of type a and returns a type return value.

Mathematically, we often write this type of operation.

The four operations are all functions that accept numbers and return numbers. We consider * 3, +2, -7 as functions multiply3, plus2, minus7, and this will be the case in functional languages

Go back to the previously mentioned container and mark the container as an M.
Suppose there is a function that takes int and returns M [int], which is written as int-> M [int]. Then we can string this type of function together.

Okay? Is that cheating? Unsurprisingly, int-> int functions can be linked together. How is int-> M [int] string? Does the return value of the first function differ from the parameters of the second function?
If you use container theory to explain this problem, it will be more difficult to understand. In my opinion, Monad also contains behavior. M [int] defines how the int inside is taken out and thrown to the next int-> M [int] function.
Is that very abstract? for example. There is an optional class in Java.

The above code uses flatMap to connect two String-> Optional functions together. flatMap is responsible for unpacking the string in optional and then throwing the string into the function as a parameter. The behavior of flatMap is defined by optional.

Why do we need a-> M [a] in addition to a-> a? And it is M [a] to solve certain problems.
From the code example above, we can directly see that our processing has such an instruction when there is no option

But do people really care about an if-statement? However, when you write a functional language it is written as a chain as much as possible, and writing too many ifs is easy to program the imperative style of programming. Have you written code similar to the following before?

If you are using Stream it is very easy to do.

Another typical example is Promise. If you've written js you may have gotten into callback hell.

One solution is a promise (now an enhanced version of aysnc is waiting for you), and then the code can be written as a chain.

Optional, Stream, Promise all use this monad concept. In addition, unpacking the container is not the same for all monads. The container has its own way of unpacking. If you are interested you can take a look. Optional is relatively easy

It seems that these things are amazing (at least when I first understood Monad), many problems were solved with a concept or idea. But does it really only exist for the beauty of the code?
Brian Beckham previously stated that monads are actually intended to limit side effects. Unfortunately, we can understand this level well. When I use my words, Monad separates the uncertain factors from the main flow of processing. It does not require many branches and can write the processing as a chain.
For example, writing a query to someone in the database could result in data being present or even the database not being connected. We can define such functions. Use Optional to represent the return value. If it is not found, we can return to empty.

Then the process of getting a person's name begins

Promises help us avoid when to call the function if the stereotype is not called.

I talked about containers. In functional languages, what is placed in the container cannot be lost.

Can this contradict our intuition? What good is it if it is not taken out?
And the answer has to pass the value in the container through the container because the return is also the container, so all operations are done in the container.
The optional example seems
Optional-> Optional-> Optional goes all the way.
Containers help us hide uncertainties. However, there is still uncertainty.
For example, it may or may not contain numbers, so of course there is no way to return a specific number. It is therefore recommended that when writing non-functional function languages, you pay attention to this detail and try to write all processing into the function that interacts with the container, rather than pulling out the contents of the container.
Sometimes I suddenly feel like this is a bit like object oriented programming. Objects are packed with data, you cannot edit the data directly, you have to process it through the object's open interface.

Talked about understanding your monad.
- can use Monad as a container
-Monad is used to control side effects (I didn't get it yet)
- The things brought into the container cannot be removed, only the container can process them. After processing, it is still returned in the form of a container
Cannot tell how deep or unique the understanding is, it can only be used as a study note for yourself. When you have a better understanding of the monad in the future, I hope to write it again.

map and flatMap

In fact, the Java code can still tell the difference.
The function accepted by map, the return value of the function, is of any ordinary type. a-> b
The function accepted by flatMap, the return value of the function must be Stream (Container) a-> M [b].

Reference article

http://www.ruanyifeng.com/blog/2015/07/monad.html
https://blog.hellojs.org/asynchronous-javascript-from-callback-hell-to-async-and-await-9b9ceb63c8e8