[Compose] 15. Applicative Functors for multiple arguments
发布日期:2021-08-25 04:21:26 浏览次数:2 分类:技术文章

本文共 1393 字,大约阅读时间需要 4 分钟。

Working our way backwards from solution to problem, we define an applicative functor, then use it to apply a function of multiple arguments.

 

For example we have this line of code:

const res = Box(x => x +1).ap(Box(2))// Box(3);

We want to use a funciton 'ap' (apply) on Box. And x will be 2.

 

To define 'ap' function.

const Box = x =>({  chain: f => f(x),  ap: other => other.map(x),  map: f => Box(f(x)),  fold: f => f(x),  inspect: () => `Box(${x})`})

So '

Box(x => x +1).ap(Box(2))

'

Can be translated to:

Box(2) => Box(2).map(x => x + 1);

 

This can be useful when apply curry function:

const res = Box(x => y => x + y).ap(Box(1)).ap(Box(2));console.log(res.inspect()); //Box(3)

after apply .ap(Box(1)), it becomes to:

Box(y => 1 +y).ap(Box(2))

after apply .ap(Box(2)), it becomes to:

Box(1 +2 )

 

It ends up, we have a function and continue to using 'ap':

const add = x => y => x + y;const res = Box(add).ap(Box(1)).ap(Box(2));

 

This partten is called click-functor!

The rule is:

F(val).map(fn) === F(fn).ap(F(val))

 

For example now we have:

const liftA2 = (fn, Fx, Fy) =>   F(fn).ap(Fx).ap(Fy);

The problem is we don't know what 'F' it is here...

So what we can do is transform accorind to the rule we have:

const liftA2 = (fn, Fx, Fy) =>   Fx.map(fn).ap(Fy)

Therefore we don't need to memtion any Functor.

 

Example:

const res2 = liftA2(add, Box(1), Box(2));console.log(res2.inspect()); //Box(3)

 

转载地址:https://blog.csdn.net/weixin_33843947/article/details/85841806 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:[OSG]OpenSceneGraph FAQ 以及OSG资源
下一篇:Maven远程仓库的配置

发表评论

最新留言

第一次来,支持一个
[***.219.124.196]2024年04月07日 18时44分03秒

关于作者

    喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!

推荐文章