gpt4 book ai didi

scala - 重复 eval T => scala.concurrent.Future[T] 到 Process[?, T]

转载 作者:行者123 更新时间:2023-12-02 03:54:27 26 4
gpt4 key购买 nike

我有一个函数get: T => scala.concurrent.Future[T]

我想像这样迭代它:

   val futs: Iterator[Future[T]] = Iterator.iterate(get(init)){
_.flatMap(prev => get(prev))
}

但是Iterator的类型是Future[T],处理这个迭代器并不容易。

How could I transfer that to Process[?, T]

(也许T => Future[T]作为上下文类型F)。

最佳答案

不是很好的解决方案,但有效

  import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.{Future => SFuture}
import scala.language.implicitConversions
import scalaz.concurrent.Task
import scalaz.stream._

implicit class Transformer[+T](fut: => SFuture[T]) {
def toTask(implicit ec: scala.concurrent.ExecutionContext): Task[T] = {
import scala.util.{Success, Failure}
import scalaz.syntax.either._
Task.async {
register =>
fut.onComplete {
case Success(v) => register(v.right)
case Failure(ex) => register(ex.left)
}
}
}
}

val init: Int = 0

def f(i: Int): SFuture[Int] = SFuture(i + 1)

val p = Process.repeatEval[Task, Int] {
var prev = init
f(prev).toTask.map(next => {prev = next; next})
}

println(p.take(10).runLog.run)

关于scala - 重复 eval T => scala.concurrent.Future[T] 到 Process[?, T],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25779692/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com