当您的计算步骤是独立的时候,可应用函子常被提及作为单子的替代品。它们经常被提到的优点之一是,在想要堆叠 applicatives 时,您不需要 transformer,因为 F[G[X]]
总是一个可应用函子。
假设我有以下函数:
def getDataOption(): Option[Data]
def getUserFuture(): Future[User]
def process(data: Data, user: User)
我希望能够优雅地堆叠以获取 Future[Option[User]]
和 Future[Option[Data]]
,并将其与 process
映射。
到目前为止,我只想到了这个(使用Cats):
Applicative[Future]
.compose[Option]
.map2(
Applicative[Future].pure(getDataOption()),
getUserFuture().map(Applicative[Option].pure))(process)
但我确定这远非理想之选。有没有更优雅和通用的方法来实现相同的功能?
OptionT
,但你也可以使用Eff(或类似的Emm)来执行(send(getDataOption) |@| send(getUserFuture)).map(process _).runOption.detach.run
,以获得一个最终的Future[Option[A]]
。 - Eric