[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: 8402 }, 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(3) .chain(three => Maybe.of(2).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.
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
2017-02-24 [SVG] Add an SVG as an Embedded Background Image
2017-02-24 [SVG] Add an SVG as a Background Image
2017-02-24 [SVG] Optimize SVGs for Better Performance using svgo
2017-02-24 [Angular] Dynamic components with ComponentFactoryResolver
2017-02-24 [Angular] Using the platform agnostic Renderer & ElementRef
2016-02-24 [Cycle.js] Hello World in Cycle.js
2016-02-24 [Cycle.js] From toy DOM Driver to real DOM Driver