繁体   English   中英

Scala 未来与任一个转型

[英]Scala Future and Either Transformation

我有一个类型的变量

val input: Future[Seq[Either[ErrorClass, Seq[WidgetCampaign]]]] = ???

我想遍历这个输入并删除所有重复的WidgetCampaign并将 output 返回为

val result: Future[Either[ErrorClass,Set[WidgetCampaign]]] = ???

我怎样才能做到这一点?

首先,可以使用map调用在Future内部完成所有处理:

input.map(process)

所以问题是编写一个在Seq[Either[ErrorClass, Seq[WidgetCampaign]]Either[ErrorClass, Set[WidgetCampaign]]之间转换的process function 。

首先制作几个类型别名以使代码更清晰的 rest。

type InType = Either[ErrorClass, Seq[WidgetCampaign]]
type OutType = Either[ErrorClass, Set[WidgetCampaign]]

这个过程本身可以通过一个尴尬的flatMap调用来完成,但是一个简单的递归 function 可能是最好的:

def process(input: Seq[InType]): OutType = {
  @annotation.tailrec
  def loop(rem: List[InType], res: Set[WidgetCampaign]): OutType =
    rem match {
      case Nil => // Stop when no more elements to process
        Right(res)
      case Left(e) :: _ => // Stop on first error
        Left(e)
      case Right(s) :: tail => // Add this Seq to the result and loop
        loop(tail, res ++ s)
    }

  loop(input.toList, Set.empty[WidgetCampaign])
}

这是递归逻辑的标准模式,其中递归 function 本身被包裹在外部 function 中。 然后内部 function 为提高效率而进行尾递归,中间结果通过递归调用向下传递。

输入被转换为List以使模式匹配更容易。

这是未经测试的,但它可以编译,所以这是一个开始......

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM