gpt4 book ai didi

scala - Scalaz 中的 State 和 Free monad 示例

转载 作者:行者123 更新时间:2023-12-04 15:22:31 27 4
gpt4 key购买 nike

有人可以举例说明如何使用 ScalaZ Free monad 吗?

例如,如果我有一个简单的 State 函数并且想要应用它 10,000 次,我会得到 StackOverflowError:

def setS(i: Int) :State[List[Int], Unit] = State { l => ( i::l, () ) }

val state = (1 to 10000).foldLeft( put(Nil :List[Int]) ) {
case (st, i) => st.flatMap(_ => setS(i))
}

state(Nil)

据我了解,Free monad 可以帮助避免这种情况。我将如何使用 Free monad 重新编写这段代码以防止堆栈溢出?

最佳答案

正如我在上面的评论中所说,解除 State计算为 StateT[Free.Trampoline, S, A]似乎它应该工作:

import scalaz._, Scalaz._, Free.Trampoline

def setS(i: Int): State[List[Int], Unit] = modify(i :: _)

val s = (1 to 10000).foldLeft(state[List[Int], Unit](()).lift[Trampoline]) {
case (st, i) => st.flatMap(_ => setS(i).lift[Trampoline])
}

s(Nil).run

不幸的是,这仍然会溢出堆栈,但正如 Dave Stevens 所指出的,使用应用 *> 进行排序。而不是 flatMap解决了这个问题:
val s = (1 to 100000).foldLeft(state[List[Int], Unit](()).lift[Trampoline]) {
case (st, i) => st *> setS(i).lift[Trampoline]
}

s(Nil).run

我不知道为什么会这样,我已经 asked a new question特别是关于差异,但这应该让您开始使用 Free .

关于scala - Scalaz 中的 State 和 Free monad 示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23965215/

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