[Compose] 15. Applicative Functors for multiple arguments

本文介绍了如何使用Applicative Functors来应用多参数函数,并通过具体的代码示例展示了其在Curry函数中的应用过程。此外,还讲解了如何利用转换规则简化操作。

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)

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值