当状态满足某些条件时如何停止状态转换?

How to stop state transition when state satisfies some condition?

我是 scalaz/cats 的新手,对 State monad 有疑问(catsscalaz 无关紧要)。考虑以下带有 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.

后知道状态是否满足条件

是否可以在 cats/scalaz 中使用 State monad 这样做,或者我需要其他东西?

您将使用由表示终止的另一个 monad 参数化的状态 monad。

一般来说,这种参数化的 monad 被称为 monad transformers。在这种特定情况下,您将使用 StateT monad 转换器。模一些实现细节,StateT等同于

type StateT[F[_], S, A] = S => F[(S, A)]

现在可以选择FOption,代表立即终止

import scalaz.StateT
import scalaz.std.option._

object StateTest {

  type Stack = List[Int]

  def main(args: Array[String]) = {
    println(transition.run(List(1, 2, 3, 4))) // Some((List(4), 3))
    println(transition.run(List(1, 2)))       // None
  }

  def transition: StateT[Option, Stack, Int] = for {
    _ <- pop
    _ <- pop
    a <- pop
  } yield a

  def pop: StateT[Option, Stack, Int] = StateT {
    case x::xs => Some((xs, x))
    case Nil   => None
  }
}

如果你想return一些B类型的值即使在提前终止的情况下,你可以使用Either[B, ?]而不是Option来参数化StateT:

type ErrorOr[A] = Either[String, A]

def pop1: StateT[ErrorOr, Stack, Int] = StateT {
  case x::xs => Right((xs, x))
  case Nil   => Left("Cannot pop from an empty stack.")
}