>我有一个类型的变量
val input: Future[Seq[Either[ErrorClass, Seq[WidgetCampaign]]]] = ???
我想遍历此输入并删除所有重复项WidgetCampaign
并将输出返回为
val result: Future[Either[ErrorClass,Set[WidgetCampaign]]] = ???
我怎样才能做到这一点?
首先,处理都可以在Future
内使用map
调用完成:
input.map(process)
所以问题是编写一个在Seq[Either[ErrorClass, Seq[WidgetCampaign]]
和Either[ErrorClass, Set[WidgetCampaign]]
之间转换的process
函数。
首先创建几个类型别名,以使代码的其余部分更清晰。
type InType = Either[ErrorClass, Seq[WidgetCampaign]]
type OutType = Either[ErrorClass, Set[WidgetCampaign]]
该过程本身可以通过一个笨拙的flatMap
调用来完成,但一个简单的递归函数可能是最好的:
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])
}
这是递归逻辑的标准模式,其中递归函数本身包装在外部函数中。然后,内部函数是尾递归的,以提高效率,中间结果通过递归调用向下传递。
输入将转换为List
,以使模式匹配更容易。
这是未经测试的,但它可以编译,所以这是一个开始......