【发布时间】:2018-05-28 21:56:20
【问题描述】:
我对 scalaz/cats 很陌生,并且对 State monad 有疑问(cats 或 scalaz 无关紧要)。考虑以下带有Stack 的著名示例:
object StateTest {
type Stack = List[Int]
def main(args: Array[String]) = {
println(transition.run(List(1, 2, 3, 4)).value) //(List(4),Some(3))
println(transition.run(List(1, 2)).value) //(List(),None)
}
def transition: State[Stack, Option[Int]] = for {
_ <- pop
_ <- pop
a <- pop
} yield a
def pop: State[Stack, Option[Int]] = State {
case x::xs => (xs, Some(x))
case Nil => (Nil, None)
}
}
问题是我想执行状态转换(pop)直到状态(List[Int])满足某些条件(我想检查List[Int]::isEmpty),然后立即停止。
在当前的实现中,我只能在调用run之后知道状态是否满足条件。
是否可以在 cat/scalaz 中使用 State monad 这样做,或者我需要其他东西?
【问题讨论】:
标签: scala functional-programming scalaz scala-cats