gpt4 book ai didi

scala - 在理解中结合列表、 future 和选项 - scalaz

转载 作者:行者123 更新时间:2023-12-01 12:29:29 25 4
gpt4 key购买 nike

我有以下问题:

val sth: Future[Seq[T, S]] = for {
x <- whatever: Future[List[T]]
y <- x: List[T]
z <- f(y): Future[Option[S]]
n <- z: Option[S]
} yield y: T -> n: S

我想让这段代码工作(我想每个人都理解这个想法,因为我添加了类型)。

我所说的“工作”是指我希望继续使用 for-comprehension 结构并最终实现预期的类型。我知道有一些“丑陋”的方法可以做到这一点,但我想学习如何做到纯粹:)

当我阅读互联网时,我得出的结论是我的问题可以通过 monad 转换器和 scalaz 解决。不幸的是,我找不到一个例子来帮助更好地理解我应该如何进行。

目前我已经尝试了 scalaz 和 Eff monad 库,但我想我仍然不明白它是如何工作的,因为我无法解决我的问题。

如有任何帮助,我将不胜感激。

编辑:它应该是序列的 future ,也关于“无论什么”,我把它作为函数的参数,很抱歉误导你

最佳答案

您可以使用 scalaz ListT monad transformer 做一些您需要的事情

 object Test {
import scalaz._
import ListT._
type T = String
type S = Int
val whatever: Future[List[T]] = ??? // you get this somewhere
def f(y: T): Future[Option[S]] = ??? // function that returns future of option

val sth: Future[List[(T, S)]] = (for {
y <- listT(whatever)
// you cannot mix list and option, but you can convert the option to a list of 1 item
n <- listT(f(y).map(_.toList))
} yield y -> n).run
}

N.B.:因为你从一个 future 开始,你不能返回一个 Seq[(T,S)],你只能有一个 future 。如果你想阻塞并得到结果,你必须调用 Await.result。

关于scala - 在理解中结合列表、 future 和选项 - scalaz,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35706046/

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