如何将 Future 的析取转换为析取的 Future

编程入门 行业动态 更新时间:2024-10-26 14:28:07
本文介绍了如何将 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 的 Zip 或 Cozip(在另一个答案中提到),但在这种情况下它更通用为具有两个类型参数的任何类型构造函数定义(假设它具有适当的语义),而不仅仅是元组或析取.

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

本文发布于:2023-11-25 03:11:46,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1628085.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:转换为   如何将   Future

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!