[Functional Programming] Monad
Before we introduce what is Monad, first let's recap what is a pointed functor:
A pointed functor is a Functor with .of() method
Why pointed Functor is imporant? here
OK, now, let's continue to see some code:
const mmo = Maybe.of(Maybe.of('nunchucks'));
// Maybe(Maybe('nunchucks'))
We don't really want nested Functor, it is hard for us to work with, we need to remember how deep is the nested Functor.
To solve the problem we can have a new method, call '.join()'.
mmo.join();
// Maybe('nunchucks')
What '.join()' does is just simply reduce one level Functor.
So how does implememation of 'join()' looks like?
Maybe.prototype.join = function join() {
return this.isNothing() ? Maybe.of(null) : this.$value;
};
As you can see, we just return 'this.$value', instead of put the value into Maybe again.
With those in mind, let's define what is Monad!
Monads are pointed functors that can flatten
Let's see a example, how to use join:
// join :: Monad m => m (m a) -> m a
const join = mma => mma.join(); // firstAddressStreet :: User -> Maybe Street
const firstAddressStreet = compose(
join,
map(safeProp('street')),
join,
map(safeHead), safeProp('addresses'),
); firstAddressStreet({
addresses: [{ street: { name: 'Mulburry', number: }, postcode: 'WC2N' }],
});
// Maybe({name: 'Mulburry', number: 8402})
For now, each map opreation which return a nested map, return call 'join' after.
Let's abstract this into a function called chain.
// chain :: Monad m => (a -> m b) -> m a -> m b
const chain = curry((f, m) => m.map(f).join()); // or // chain :: Monad m => (a -> m b) -> m a -> m b
const chain = f => compose(join, map(f));
Now we can rewrite the previous example which .chain():
// map/join
const firstAddressStreet = compose(
join,
map(safeProp('street')),
join,
map(safeHead),
safeProp('addresses'),
); // chain
const firstAddressStreet = compose(
chain(safeProp('street')),
chain(safeHead),
safeProp('addresses'),
);
To get a feelings about chain, we give few more examples:
// getJSON :: Url -> Params -> Task JSON
getJSON('/authenticate', { username: 'stale', password: 'crackers' })
.chain(user => getJSON('/friends', { user_id: user.id }));
// Task([{name: 'Seimith', id: 14}, {name: 'Ric', id: 39}]); // querySelector :: Selector -> IO DOM
querySelector('input.username')
.chain(({ value: uname }) => querySelector('input.email')
.chain(({ value: email }) => IO.of(`Welcome ${uname} prepare for spam at ${email}`)));
// IO('Welcome Olivia prepare for spam at olivia@tremorcontrol.net'); Maybe.of()
.chain(three => Maybe.of().map(add(three)));
// Maybe(5); Maybe.of(null)
.chain(safeProp('address'))
.chain(safeProp('street'));
// Maybe(null);
Theory
The first law we'll look at is associativity, but perhaps not in the way you're used to it.
// associativity
compose(join, map(join)) === compose(join, join);
These laws get at the nested nature of monads so associativity focuses on joining the inner or outer types first to achieve the same result. A picture might be more instructive:

The second law is similar:
// identity for all (M a)
compose(join, of) === compose(join, map(of)) === id;
It states that, for any monad M, of and join amounts to id. We can also map(of) and attack it from the inside out. We call this "triangle identity" because it makes such a shape when visualized:

Now, I've seen these laws, identity and associativity, somewhere before... Hold on, I'm thinking...Yes of course! They are the laws for a category. But that would mean we need a composition function to complete the definition. Behold:
const mcompose = (f, g) => compose(chain(f), g); // left identity
mcompose(M, f) === f; // right identity
mcompose(f, M) === f; // associativity
mcompose(mcompose(f, g), h) === mcompose(f, mcompose(g, h));
They are the category laws after all. Monads form a category called the "Kleisli category" where all objects are monads and morphisms are chained functions. I don't mean to taunt you with bits and bobs of category theory without much explanation of how the jigsaw fits together. The intention is to scratch the surface enough to show the relevance and spark some interest while focusing on the practical properties we can use each day.
[Functional Programming] Monad的更多相关文章
- [Functional Programming Monad] Refactor Stateful Code To Use A State Monad
When we start to accumulate functions that all work on a given datatype, we end up creating a bunch ...
- [Functional Programming Monad] Apply Stateful Computations To Functions (.ap, .liftA2)
When building our stateful computations, there will come a time when we’ll need to combine two or mo ...
- [Functional Programming Monad] Combine Stateful Computations Using Composition
We explore a means to represent the combination of our stateful computations using familiar composit ...
- [Functional Programming Monad] Combine Stateful Computations Using A State Monad
The true power of the State ADT really shows when we start combining our discrete, stateful transact ...
- [Functional Programming Monad] Modify The State Of A State Monad
Using put to update our state for a given state transaction can make it difficult to modify a given ...
- [Functional Programming Monad] Substitute State Using Functions With A State Monad (get, evalWith)
We take a closer look at the get construction helper and see how we can use it to lift a function th ...
- [Functional Programming Monad] Map And Evaluate State With A Stateful Monad
We explore our first stateful transaction, by devising a means to echo our state value into the resu ...
- Functional Programming without Lambda - Part 2 Lifting, Functor, Monad
Lifting Now, let's review map from another perspective. map :: (T -> R) -> [T] -> [R] accep ...
- Monad (functional programming)
In functional programming, a monad is a design pattern that defines how functions, actions, inputs, ...
随机推荐
- SCU 4443 Range Query
二分图最大匹配,枚举. 可以计算出每一个位置可以放哪些数字,每个数字可以放在哪些位置,这样就可以建二分图了. 如果二分图最大匹配不到$n$,则无解.否则构造字典序最小的解,可以枚举每一位放什么数字,然 ...
- Python类总结-析构函数和__call__方法
class Foo: def __init__(self): pass #析构函数 def __del__(self): print('解释器要销毁我了,我要做最后一次呐喊') def __call_ ...
- Eclipse酷炫项目、最新趋势介绍
作为Eclipse基金组织的执行董事,我需要经常审阅每一个新提交的Eclipse项目协议书.作为Eclipse的一分子,我很乐意与加入我们团队的新开发人员互动.这也是我工作中的乐趣之一.2013年,我 ...
- CSS 笔记——列表表格
6. 列表表格 -> 列表 (1)list-style 基本语法 list-style : list-style-image || list-style-position || list-sty ...
- vijos Warcraft III 守望者的烦恼
题解 转移方程好写吧 一个一维递推式 然后我们可以构造矩阵优化 嗯,最近学一下递推优化 代码 #include<cstdio> #include<cstring> #inclu ...
- BZOJ2303 APIO2011方格染色
这题太神了 首先我们可以发现只有当i和j都是偶数时a[1][1]^a[1][j]^a[i][1]^a[i][j]=1才满足情况,其它时都为0 所以我们可以先把i和j都为偶数的地方^1变为0 下面才是最 ...
- 51nod1624 取余最长路 前缀和 + set
由于只有3行,因此只会会换行2次,假设$x, y$分别为这两次的换行点 那么答案为$S[1][x] +S[2][y] - S[2][x - 1] + S[3][n] - S[3][y - 1]$ 其中 ...
- BZOJ2754 [SCOI2012]喵星球上的点名 SA+莫队+树状数组
题面 戳这里 题解 首先先把所有给出的姓名和询问全部接在一起,建出\(height\)数组. 某个串要包含整个询问串,其实就相当于某个串与询问串的\(lcp\)为询问串的长度. 而两个后缀\(Suff ...
- day78_淘淘商城项目_11_单点登录系统实现 + 用户名回显 + ajax请求跨域问题详解_匠心笔记
课程计划 1.SSO注册功能实现 2.SSO登录功能实现 3.通过token获得用户信息 4.ajax跨域请求解决方案--jsonp 1.服务接口实现 SSO系统就是解决分布式环境下登录问题的,本 ...
- ADC Power Supplies
http://www.planetanalog.com/author.asp?section_id=3041&doc_id=563055 Jonathan Harris, Product Ap ...