Ok, about Monad, I am aware that there are enough questions having been asked. I am not trying to bother anyone to ask what is monad again.
Actually, I read What is a monad?, it is very helpful. And I feel I am very close to really understand it.
I create this question here is just to describe some of my thoughts on Monad and Function, and hope someone could correct me or confirm it correct.
Some answers in that post let me feel monad is a little bit like function.
Monad takes a type, return a wrapper type (return
), also, it can take a type, doing some operations on it and returns a wrapper type (bind
).
From my point of view, it is a little bit like function. A function takes something and do some operations and return something.
Then why we even need monad? I think one of the key reasons is that monad provides a better way or pattern for sequential operations on the initial data/type.
For example, we have an initial integer i
. In our code, we need to apply 10 functions f1, f2, f3, f4, ..., f10
step by step, i.e., we apply f1
on i
first, get a result, and then apply f2
on that result, then we get a new result, then apply f3
...
We can do this by functions rawly, just like f1 i |> f2 |> f3...
. However, the intermediate results during the steps are not consistent; Also if we have to handle possible failure somewhere in middle, things get ugly. And an Option
anyway has to be constructed if we don't want the whole process fail on exceptions. So naturally, monad
comes in.
Monad unifies and forces the return types in all steps. This largely simplifies the logic and readability of the code (this is also the purpose of those design patterns
, isn't it). Also, it is more bullet proof against error or bug. For example, Option Monad
forces every intermediate results to be options
and it is very easy to implement the fast fail
paradigm.
Like many posts about monad described, monad is a design pattern and a better way to combine functions / steps to build up a process.
Am I understanding it correctly?
See Question&Answers more detail:
os