我有一个类型的变量
val input: Future[Seq[Either[ErrorClass, Seq[WidgetCampaign]]]] = ???
我想遍历此输入并删除所有重复项WidgetCampaign
,然后将输出返回为
val result: Future[Either[ErrorClass,Set[WidgetCampaign]]] = ???
我该如何实现?
首先,可以使用Future
调用在map
内部完成所有处理:
input.map(process)
所以问题是编写一个在process
和Seq[Either[ErrorClass, Seq[WidgetCampaign]]
之间转换的Either[ErrorClass, Set[WidgetCampaign]]
函数。
首先创建几个类型别名,以使其余代码更简洁。
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
以使模式匹配更加容易。
未经测试,但可以编译,因此是一个开始...