[英]How to map a wrapped value in fp-ts?
I have this code and I was wondering if I can transform the below pipe
s into just one pipe
?我有这段代码,我想知道是否可以将下面的
pipe
转换为一个pipe
?
const result: TE.TaskEither<DataTransferError, readonly CoinMetadataDto[]> = pipe(
this.ensureFundsExist(),
TE.chain((funds) => {
return pipe(
funds.map((fund) => {
return this.coinGeckoAdapter.getCoinMetadata(fund.coinGeckoId);
}),
TE.sequenceArray,
);
}),
);
In other words can I map
a TaskEither<E, Data[]>
into a TaskEither<E, OtherData[]>
in one go?换句话说,我可以一次
map
TaskEither<E, Data[]>
映射到TaskEither<E, OtherData[]>
吗?
Instead of using Array.prototype.map
( funds.map
), you can use the curried map
from the ReadonlyArray
fp-ts module.您可以使用
ReadonlyArray
fp-ts 模块中的柯里化map
,而不是使用Array.prototype.map
( funds.map
)。 Combine this with flow
(left-to-right function composition) and you can get rid of the nested pipe
:将此与
flow
(从左到右的函数组合)结合起来,您可以摆脱嵌套pipe
:
import * as RA from 'fp-ts/ReadonlyArray'
const result: TE.TaskEither<DataTransferError, readonly CoinMetadataDto[]> = pipe(
this.ensureFundsExist(),
TE.chain(
flow(
RA.map(fund => this.coinGeckoAdapter.getCoinMetadata(fund.coinGeckoId)),
TE.sequenceArray
)
)
);
However, there's an even better way of doing this using traverseArray
:但是,使用
traverseArray
有更好的方法:
export declare const traverseArray: <A, B, E>(
f: (a: A) => TaskEither<E, B>
) => (as: readonly A[]) => TaskEither<E, readonly B[]>
TE.traverseArray(f)
is equivalent to flow(RA.map(f), TE.sequenceArray)
. TE.traverseArray(f)
等价于flow(RA.map(f), TE.sequenceArray)
。
const result: TE.TaskEither<DataTransferError, readonly CoinMetadataDto[]> = pipe(
this.ensureFundsExist(),
TE.chain(
TE.traverseArray(fund =>
this.coinGeckoAdapter.getCoinMetadata(fund.coinGeckoId)
)
)
);
For more information, have a look at the Traversable
type class.有关更多信息,请查看
Traversable
类型类。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.