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 Mof 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.

More detail

[Functional Programming] Monad的更多相关文章

  1. [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 ...

  2. [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 ...

  3. [Functional Programming Monad] Combine Stateful Computations Using Composition

    We explore a means to represent the combination of our stateful computations using familiar composit ...

  4. [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 ...

  5. [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 ...

  6. [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 ...

  7. [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 ...

  8. Functional Programming without Lambda - Part 2 Lifting, Functor, Monad

    Lifting Now, let's review map from another perspective. map :: (T -> R) -> [T] -> [R] accep ...

  9. Monad (functional programming)

    In functional programming, a monad is a design pattern that defines how functions, actions, inputs, ...

随机推荐

  1. UVA10298 Power Strings [KMP]

    题目传送门 Power Strings 格式难调,题面就不放了. 一句话题意,求给定的若干字符串的最短循环节循环次数. 输入样例#1: abcd aaaa ababab . 输出样例#1: 1 4 3 ...

  2. mongodb 32系统安装失败问题

    32位系统 在安装完成后 运行mongod --dbpath c:\data\db后,没有如愿以偿出现端口数字27017,出现了如下的报错 ************** D:\GREENT~1\Pow ...

  3. esxi上引起vm绑定浮动IP无法和外面通信

    在vmware esxi环境通过创建VM安装完成openstack之后,发现创建Instance后网络不通,经过多方面排查,最后确定是vmware esxi标准交换机拒绝“混杂模式”所致,故打开“混杂 ...

  4. Elasticsearch 删除索引下的所有数据

    下面是head中操作的截图 #清空索引 POST quality_control/my_type/_delete_by_query?refresh&slices=5&pretty { ...

  5. 【BZOJ 3958】 3958: [WF2011]Mummy Madness (二分+扫描线、线段树)

    3958: [WF2011]Mummy Madness Time Limit: 10 Sec  Memory Limit: 256 MBSubmit: 96  Solved: 41 Descripti ...

  6. BZOJ4551 HEOI2016树

    可以用并查集,记忆化搜索,线段树多种方法实现. 我这里写的是依照dfs序建线段树,维护区间最大值. #include<bits/stdc++.h> using namespace std; ...

  7. UVA11107 Life Forms --- 后缀数组

    UVA11107 Life Forms 题目描述: 求出出现在一半以上的字符串内的最长字符串. 数据范围: \(\sum len(string) <= 10^{5}\) 非常坑的题目. 思路非常 ...

  8. 【BFS】【map】hdu5925 Coconuts

    题意:一张n*m的网格图(n和m可以达到10^9),其中K个点是障碍物(不超过200个),问你没有被障碍物占据的点形成了几个连通块?并且输出各个连通块的大小. 容易证明,大小超过40000的连通块最多 ...

  9. SHELL异常处理(转载)

    写SHELL好久了,经常被异常困扰,可竟然坚持了若干年没用过,回想以前服务过的公司,阿弥陀佛,罪过罪过.废话少说,希望此篇文章可以协助大家和我彻底结束SHELL脚本就是LINUX命令集合的初级阶段. ...

  10. bzoj 3224 普通平衡树 vactor的妙用

    3224: Tyvj 1728 普通平衡树 Time Limit: 1 Sec  Memory Limit: 256 MB 题目连接 http://www.lydsy.com/JudgeOnline/ ...