簡體   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