如何将 Future 的析取转换为析取的 Future [英] How to transform disjunction of Future to Future of disjunction

查看:69
本文介绍了如何将 Future 的析取转换为析取的 Future的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个方法的结果:val res: Future[Int] Xor Future[String] = getResult(x)

并想对其进行转换并将其用作Future[Int Xor String]

and would like to transform it and use it as Future[Int Xor String]

我无法从 牧猫博客 并且不确定 monad 转换器是否是这里的正确工具,也许是某种形式的 traverse?

I could not extrapolate my use case from the herding cats blog and am not sure whether a monad transformer would be the right tool here, perhaps rather some form of traverse?

Xor 代表任何分离.Scalaz \/ 或 stdlib Either 也可以(尽管我更喜欢有偏见的分离).

Xor from cats stands in for any disjunction. Scalaz \/ or stdlib Either would be fine as well (though I would prefer a biased disjunction).

谢谢

推荐答案

Just as sequence 允许您将 F[G[A]] 转换为 G[F[A]]F 有一个 Traverse 实例并且 G 适用时,bisequence 让你把 F[G[A], G[B]] 变成 G[F[A, B]] 如果 F 有一个 Bitraverse 实例(G 是适用的).

Just as sequence allows you to turn a F[G[A]] into a G[F[A]] when F has a Traverse instance and G is applicative, bisequence lets you turn a F[G[A], G[B]] into a G[F[A, B]] if F has a Bitraverse instance (and G is applicative).

Cats 已经为至少几个版本提供了一个Bittraverse实现(我在这里使用 0.6.0-M2),所以你可以这样写:

Cats has provided a Bitraverse implementation for at least a couple of versions (I'm using 0.6.0-M2 here), so you can just write this:

import cats.data.Xor, cats.std.future._, cats.syntax.bitraverse._
import scala.concurrent.Future
import scala.concurrent.ExecutionContext.Implicits.global

def flip[A, B](x: Xor[Future[A], Future[B]]): Future[Xor[A, B]] = x.bisequence

Bittraverse 有点像 Scalaz 的 ZipCozip(在另一个答案中提到),但在这种情况下它更通用为具有两个类型参数的任何类型构造函数定义(假设它具有适当的语义),而不仅仅是元组或析取.

Bitraverse is a little like Scalaz's Zip or Cozip (mentioned in the other answer), but it's more generic in that instances can be defined for any type constructor with two type arguments (assuming it has the appropriate semantics), not just tuples or disjunction.

这篇关于如何将 Future 的析取转换为析取的 Future的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆