简体   繁体   English

Scala 未来与任一个转型

[英]Scala Future and Either Transformation

I have a variable of type我有一个类型的变量

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

I want to traverse this input and remove all duplicates WidgetCampaign and return the output as我想遍历这个输入并删除所有重复的WidgetCampaign并将 output 返回为

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

How can I achieve this?我怎样才能做到这一点?

Firstly, the processing can all be done inside the Future using a map call:首先,可以使用map调用在Future内部完成所有处理:

input.map(process)

So the problem is to write a process function that converts between Seq[Either[ErrorClass, Seq[WidgetCampaign]] and Either[ErrorClass, Set[WidgetCampaign]] .所以问题是编写一个在Seq[Either[ErrorClass, Seq[WidgetCampaign]]Either[ErrorClass, Set[WidgetCampaign]]之间转换的process function 。

Start by making a couple of type aliases to make the rest of the code cleaner.首先制作几个类型别名以使代码更清晰的 rest。

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

The process itself can be done with an awkward flatMap call, but a simple recursive function is probably best:这个过程本身可以通过一个尴尬的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])
}

This is a standard pattern for recursive logic where the recursive function itself is wrapped in an outer function.这是递归逻辑的标准模式,其中递归 function 本身被包裹在外部 function 中。 The inner function is then tail-recursive for efficiency, with the intermediate result being passed down through the recursive call.然后内部 function 为提高效率而进行尾递归,中间结果通过递归调用向下传递。

The input is converted to a List to make pattern matching easier.输入被转换为List以使模式匹配更容易。

This is untested, but it compiles so that's a start...这是未经测试的,但它可以编译,所以这是一个开始......

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

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