[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, ...
随机推荐
- 深度学习基础系列(三)| sigmoid、tanh和relu激活函数的直观解释
常见的激活函数有sigmoid.tanh和relu三种非线性函数,其数学表达式分别为: sigmoid: y = 1/(1 + e-x) tanh: y = (ex - e-x)/(ex + e-x) ...
- poj1860 & poj2240(Bellman-Ford)
1860的思路是将可以换得的不同种的货币的数量当作节点,每个兑换点当成边,然后我抄了个算法导论里面的Bellman-Ford算法,一次就过了.看discussion里面很多讨论精度的,我想都没想过…… ...
- pool创建多进程
这中方式用的比较多,毕竟要控制并发数量,不可能不限制并发数 #_*_coding:utf-8_*_ from multiprocessing import Pool import time def f ...
- Python实现简单的API接口
get方法 代码实现 # coding:utf-8 import json from urlparse import parse_qs from wsgiref.simple_ ...
- java8新特性——简介
java8问世已经有好长时间了,但是之前项目中都没有使用到,所以一直都只是了解一些,近期刚刚换了家新公司,在开发中需要使用到java8来开发,所以也是马上赶来学习一下java8得新特性. 一.新特性 ...
- 初识Linux 基础操作
Linux常用指令: 在Linux中如果不懂基础命令,在Linux中将寸步难行,下面是我在初学Linux系统时总结的一些基本命令. 1.基础命令 ls ...
- HDU 1213(并查集)
How Many Tables Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)T ...
- 【BZOJ 3238】 3238: [Ahoi2013]差异(SAM)
3238: [Ahoi2013]差异 Time Limit: 20 Sec Memory Limit: 512 MBSubmit: 3047 Solved: 1375 Description In ...
- 我的OI生涯 第一章
第一章 一入电竞深似海 我叫WZY,是TSYZ的一名学生. 2016年7月10日,我进了一个叫做oi的坑. 那时的我不知道什么叫竞赛,不知道什么叫编程,不知道什么是c++. 就记得前一天我特意去图 ...
- HDU 4612 Warm up tarjan 树的直径
Warm up 题目连接: http://acm.hdu.edu.cn/showproblem.php?pid=4612 Description N planets are connected by ...