Scalaz - 无法取消应用类型StateT [Future,Foo,Bar]

时间:2015-02-04 08:54:42

标签: scala scalaz

我有一个l的列表StateT[Id, MyState, Boolean]

有了它,我能够做到以下几点:

case class MyState (s: String)

val startState = MyState ("s")

val l: List[StateT[Id, MyState, Boolean]] = ...

val failed = l.sequenceU.map { x => }
 .map { _.foldMap (identity)(Monoid.instance (_ | _, false)) }
 .eval (startState)

这将通过列表中的所有内容逐个管理状态,然后将所有结果与按位OR(|)组合。

我现在想要将我的列表更改为StateT[Future, MyState, Boolean]类型,但是我很难将其编译。编译器无法确定我需要做什么才能使其编译。编译器告诉我,我需要能够编译implicitly[Unapply[Applicative, StateT[Future, MyState, MyResult]]],现在我不能,我的问题是如何隐含地定义我需要的东西?

以下内容在REPL上重现错误:

scala> import scalaz._
import scalaz._

scala> import scalaz.Id._
import scalaz.Id._

scala> import scala.concurrent.Future
import scala.concurrent.Future

scala> case class MyState (s: String)
defined class MyState

scala> case class MyResult (r: String)
defined class MyResult

scala> implicitly[Unapply[Applicative, StateT[Id, MyState, MyResult]]]
res0: scalaz.Unapply[scalaz.Applicative,scalaz.StateT[scalaz.Id.Id,MyState,MyResult]] = scalaz.Unapply_2$$anon$5@5443fcf1

scala> implicitly[Unapply[Applicative, StateT[Future, MyState, MyResult]]]
<console>:55: error: Unable to unapply type `scalaz.StateT[scala.concurrent.Future,MyState,MyResult]` into a type constructor of kind `M[_]` that is classified by the type class `scalaz.Applicative`
1) Check that the type class is defined by compiling `implicitly[scalaz.Applicative[<type constructor>]]`.
2) Review the implicits in object Unapply, which only cover common type 'shapes'
(implicit not found: scalaz.Unapply[scalaz.Applicative, scalaz.StateT[scala.concurrent.Future,MyState,MyResult]])
              implicitly[Unapply[Applicative, StateT[Future, MyState, MyResult]]]
                        ^

有趣的是以下编译:

 scala> implicitly[Unapply[Applicative, StateT[Option, MyState, MyResult]]]
res2: scalaz.Unapply[scalaz.Applicative,scalaz.StateT[Option,MyState,MyResult]] = scalaz.Unapply_2$$anon$5@265a640

这让我觉得它必须与StateT上的Future类型相关联,或许某些Future未定义?

我使用的是Scalaz 7.0.5,我知道它没有Monad[Future],但我正在导入:

https://github.com/typelevel/scalaz-contrib/blob/v0.1.5/scala210/main/scala/Future.scala

另外,我在使用Scalaz 7.1.0的REPL上测试了这个,我得到了同样的错误。

非常感谢任何帮助!

干杯!

1 个答案:

答案 0 :(得分:3)

这有点棘手,但是......实际上你需要在范围内有一个隐含的ExecutionContext

scala> import scalaz.contrib.std.scalaFuture._
import scalaz.contrib.std.scalaFuture._

scala> import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.ExecutionContext.Implicits.global

scala> implicitly[Unapply[Applicative, StateT[Future, MyState, MyResult]]]
res14: scalaz.Unapply[scalaz.Applicative,scalaz.StateT[scala.concurrent.Future,MyState,MyResult]] = scalaz.Unapply_2$$anon$5@4c167067

在这种特殊情况下,Unapply需要Applicative的{​​{1}}个实例,而this method需要一个Future