在scala中堆叠Monad变形金刚

时间:2016-07-21 16:10:52

标签: scala haskell monads scalaz monad-transformers

我试图以haskell方式堆叠scalaz的monad transfromers:

statyReader :: (MonadReader Int m, MonadState Int m) => m Int

阶:

  def statyReader[F[_]](implicit r: MonadReader[F, Int], s: MonadState[F, Int]): F[Int] = for {
    counter <- s.get
    secret  <- r.ask
    _       <- s.put(counter + secret)
  } yield counter

它使用1隐式传递编译,但不包含2:

Error:(13, 18) value flatMap is not a member of type parameter F[Int]
    counter <- s.get
                 ^
Error:(14, 18) value flatMap is not a member of type parameter F[Int]
    secret  <- r.ask
                 ^
Error:(15, 21) value map is not a member of type parameter F[Unit]
    _       <- s.put(counter + secret)
                    ^

为什么会这样?我的猜测是编译器现在混淆了F[_]&#34;&#34; monadic实例Monad[F[_]&#34;它应该选择(MonadReader和MonadState都扩展Warning - 12200 Schema validation warning The provided XML does not conform to the Twilio Markup XML schema. Please refer to the specific error and correct the problem. )。这是一个正确的猜测吗?

如何克服这个问题?

1 个答案:

答案 0 :(得分:1)

这不是一个真正的答案,但也许有点帮助。

我认为你是对的;似乎编译器无法统一两个参数的F[_]类型(我猜因为它是具有多个可能实例而不是具体类型实例的高级类型)到monad类型。编译使用单独的参数列表,因为类型统一仅在参数列表中发生。它可以进一步说明如下:

def statyReader[F[_]](implicit r: MonadReader[F, Int], s: MonadState[F, Int]): F[Int] =
  statyReader2(r, s)

def statyReader2[F[_]:Monad](r: MonadReader[F, Int], s: MonadState[F, Int]): F[Int] =
  for {
    counter <- s.get
    secret <- r.ask
    _ <- s.put(counter + secret)
  } yield counter

Error: ambiguous implicit values: both
value s of type scalaz.MonadState[F,Int] and
value r of type scalaz.MonadReader[F,Int]
match expected type scalaz.Monad[F]

显然,作为一种解决方法,您可以使用两个参数列表来选择要使用的monad:

def statyReader[F[_]](implicit r: MonadReader[F, Int], s: MonadState[F, Int]): F[Int] =
  statyReader2(r)(s)

def statyReader2[F[_]](r: MonadReader[F, Int])(implicit s: MonadState[F, Int]): F[Int] =
  for {
    counter <- s.get
    secret <- r.ask
    _ <- s.put(counter + secret)
  } yield counter