本文介绍了Trascalolining scalaz'Monad.whileM_以防止堆栈溢出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用scalaz'Monad.whileM_以如下方式实现while循环:

I'm using scalaz' Monad.whileM_ to implement a while loop in a functional way as follows:

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))
  }
}

虽然这适用于小型k,但会导致大型k(例如1000000)的StackOverflow错误.有没有办法蹦床whileM_或有更好的方法来保证堆栈安全?

While this works for small k, it results in a StackOverflow error for large k (e.g. 1000000). Is there a way to trampoline whileM_ or is there a better way to be stack safe?

推荐答案

使用scalaz.Free.Trampoline代替scalaz.Id.Id.

type IStateT[A] = StateT[Trampoline, IState, A]

此处使用的状态操作返回State[S, A],这只是StateT[Id, S, A]的别名.您需要使用在StateT上定义的lift[M[_]]函数将StateT[Id, S, A]提升到StateT[Trampoline, S, A].

The state operations used here return State[S, A] which is just an alias for StateT[Id, S, A]. You need to use the lift[M[_]] function defined on StateT to lift StateT[Id, S, A] to StateT[Trampoline, S, A].

def eval(k: Int): MTrans[Int] = {
  for {
    state <- get[IState].lift[Trampoline].liftM[MTransT]
    _ <- put(state.copy(s = (state.s + 1) % k)).lift[Trampoline].liftM[MTransT]
  } yield (k + 1)
}

def evalCond(): MTrans[Boolean] = {
  for {
    state <- get[IState].lift[Trampoline].liftM[MTransT]
  } yield (state.s != 0)
}

最后,调用.run(IState(1))现在将导致Trampoline[(IState, String \/ Unit)].您还必须另外run此.

Finally, calling .run(IState(1)) now results in Trampoline[(IState, String \/ Unit)]. You must additionally run this as well.

eval(k).whileM_(evalCond()).run(IState(1)).run

这篇关于Trascalolining scalaz'Monad.whileM_以防止堆栈溢出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-13 22:00