Scala中的Monad Transformer堆栈



我正在学习Scala中的单子转换器,但我遇到了一个问题,我发现到目前为止无法解决。在我的单子转换器堆栈中,我组成了Either单子和State单子。但是,我没有调用属于两个单子之一的函数:

import scalaz._
import Scalaz._
object Minimal {
  type Inner[A] = EitherT[Id, String, A]
  type Outer[F[+_], A] = StateT[F,Int,A]
  type Stack[A] = Outer[Inner, A]
  def foo:Stack[Int] = for {
    n <- get[Int]
  } yield {
    2 * n
  }
  def main(args: Array[String]): Unit = {
    val x = foo.eval(8)
    println(x)
  }
}

失败,并显示以下错误消息:

[error] Minimal.scala:10: type mismatch;
[error]  found   : scalaz.IndexedStateT[scalaz.Id.Id,Int,Int,Int]
[error]  required: Minimal.Stack[Int]
[error]     (which expands to)  scalaz.IndexedStateT[Minimal.Inner,Int,Int,Int]
[error]     n <- get[Int]

如果我将monad transformer堆栈更改为:

type Stack[A] = State[Int,A]

程序编译和运行没有问题。有人知道我哪里做错了吗?

方法调用get[Int]返回一个IndexedStateT[Id, Int, Int, Int]。您的Stack[Int]扩展到IndexedStateT[Inner, Int, Int, Int],其中InnerEitherT[Id, String, A]。这有点难以推理,所以我将简化您的示例。

我们用Option代替Inner类型别名创建StateT

type Stack[A] = StateT[Option, Int, A]

get[Int]的赋值仍然会失败。

val x:Stack[Int] = get[Int]
//type mismatch; 
//  found : scalaz.State[Int,Int]
//    (which expands to) scalaz.IndexedStateT[scalaz.Id.Id,Int,Int,Int]
//  required: Minimal.Stack[Int] 
//    (which expands to) scalaz.IndexedStateT[Option,Int,Int,Int]

为了解决这个问题,我们需要将变压器lift设置为Option:

val x:Stack[Int] = get[Int].lift[Option]

如果将其转换为示例代码,则需要将liftState转换为Inner。注意,您还需要将Inner的定义更改为协变:

type Inner[+A] = EitherT[Id, String, A]
type Stack[A] = StateT[Inner, Int, A]
val x:Stack[Int] = get[Int].lift[Inner]

为了能够在不手动提升的情况下编写此代码,您可以引入隐式转换。完整的示例:

type Inner[+A] = EitherT[Id, String, A]
type Outer[F[+_], A] = StateT[F, Int, A]
type Stack[A] = Outer[Inner, A]
implicit def liftToStack[A](x:Outer[Id, A]):Stack[A] = x.lift[Inner]
def foo: Stack[Int] = for {
  n <- get[Int]
} yield {
  2 * n
}

我开始写这篇文章是作为对EECOLOR的答案的评论(我刚刚为其投票,并且我推荐它-除了最后的隐式转换),但是它有点笨拙,所以这里有一个新的答案。

EECOLOR的诊断是完全正确的,但是MonadState(我在今天早上回答你的另一个问题时使用的)让你避免了明确的提升。例如,您可以这样写:

import scalaz._, Scalaz._
type Inner[+A] = EitherT[Id, String, A]
type Stack[S, +A] = StateT[Inner, S, A]
def foo: Stack[Int, Int] = for {
  n <- MonadState[Stack, Int].get
} yield 2 * n

请注意(就像我之前的问题一样),我已经将Stack更改为状态类型的参数化。您可以轻松地将其更改为如下内容:

type MyState[S, +A] = StateT[Inner, S, A]
type Stack[+A] = MyState[Int, A]

如果您想捕获堆栈中的状态类型

最新更新