我正在使用 scalaz'Monad.whileM_
以功能方式实现 while 循环,如下所示:
object Main {
import scalaz._
import Scalaz._
import scala.language.higherKinds
case class IState(s: Int)
type IStateT[A] = StateT[Id, IState, A]
type MTransT[S[_], A] = EitherT[S, String, A]
type MTrans[A] = MTransT[IStateT, A]
def eval(k: Int): MTrans[Int] = {
for {
state <- get[IState].liftM[MTransT]
_ <- put(state.copy(s = (state.s + 1) % k)).liftM[MTransT]
} yield (k + 1)
}
def evalCond(): MTrans[Boolean] = {
for {
state <- get[IState].liftM[MTransT]
} yield (state.s != 0)
}
def run() = {
val k = 10
eval(k).whileM_(evalCond()).run(IState(1))
}
}
虽然这适用于 small k
,但它会导致大型 StackOverflow 错误k
(例如 1000000)。有没有办法蹦床whileM_
或者有更好的方法来保证堆栈安全?