[Functional Programming] Arrow Functor with contramap

本文介绍了Arrow Functor,它能提升特定类型函数并实现懒执行,可将执行拆分为不同路径。还通过示例展示了如何结合使用Arrow和contramap,当输入数据类型不匹配时,用contramap处理输入参数,避免修改原函数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

What is Arrow Functor?

Arrow is a Profunctor that lifts a function of type a -> b and allows for lazy execution of the function. Arrow can be considered a Strong Profunctorif the underlying data running through the Arrow is a Pair, typically in the form of Arrow (Pair a c) (Pair b d).

This will allow you to split execution into two distinct paths, applying Arrow to a specific path. The parameters of Arrow represent the function that it wraps, with the input being on the left, and the output on the right. When anArrow wraps an endomorphism, the signature typically represents both the input and output.

In short, Arrow is

  • Take a function
  • Function will be lazy
  • We can apply params later
const Arrow = require('crocks/Arrow');

const arrUpper = Arrow(
    str => str.toUpperCase()
)

log(
    arrUpper.runWith('zhentian')
) // ZHENTIAN

 

Why this can be useful? 

In this post, we are going to see an exmple about how to use 'Arrow' with 'contramap':

 

Currently 'arrUpper' take a string as input, sometimes the data we receive might be is an Object:

// {name: 'zhentian'}

In this case, we cannot directly using 'arrUpper', and we don't want to modify our 'arrUpper' function to be:

const arrUpper = Arrow(o => o.name && o.name.toUpperCase())

What we can do is using 'contramap' to apply an function on the input param of 'arrUpper', to change the Object type to String type, we can keep the 'arrUpper' untouched:

const Arrow = require('crocks/Arrow');
const chain = require('crocks/pointfree/chain');
const option = require('crocks/pointfree/option');
const prop = require('crocks/Maybe/prop');
const safe = require('crocks/Maybe/safe');

const getName = compose(
    option('no name'),
    chain(safe(isString)),
    prop('name')
)
const arrUpper = Arrow(
    str => str.toUpperCase()
)
const nameUpper = arrUpper
    .contramap(getName)

log(
    nameUpper.runWith({name: 'zhentian'})
) // ZHENTIAN

 

What 'contramap' does is apply the given function (getName) to the target function (arrUpper)'s params ({name: 'zhentian'}), before the target function get invoked.

So in our example, we transform the {name: 'zhentian'} to just 'zhentian' or 'no name' before passing to arrUpper.

转载于:https://www.cnblogs.com/Answer1215/p/10569099.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值