2015-12-22 44 views
3

我正在嘗試使用Scalaz EitherT與scala.concurrent.Future。當試圖用它換理解:當使用scala.concurrent.Future與EitherT時缺少Functor和Monad實例

import scalaz._ 
import Scalaz._ 

val et1:EitherT[Future, String, Int] = EitherT(Future.successful(1.right)) 

val et2:EitherT[Future, String, String] = EitherT(Future.successful("done".right)) 

val r:EitherT[Future, String, String] = for { 
    a <- et1 
    b <- et2 
} yield (s"$a $b") 

我得到以下缺失的函子和單子實例錯誤:

could not find implicit value for parameter F: scalaz.Functor[scala.concurrent.Future] 
b <- et2 
^
could not find implicit value for parameter F: scalaz.Monad[scala.concurrent.Future] 
a <- et1 

是否scalaz定義函子和單子實例的未來?如果沒有,還有其他庫提供這些實例還是我需要編寫它們?

回答

9

您需要在範圍內隱含ExecutionContextimport ExecutionContext.Implicits.global會讓你的global execution context

完整的示例:

import scala.concurrent.ExecutionContext.Implicits.global 

    import scalaz._ 
    import Scalaz._ 

    val et1:EitherT[Future, String, Int] = EitherT(Future.successful(1.right)) 

    val et2:EitherT[Future, String, String] = EitherT(Future.successful("done".right)) 

    val r:EitherT[Future, String, String] = for { 
    a <- et1 
    b <- et2 
    } yield s"$a $b" 

    val foo = Await.result(r.run, 1 seconds) 
    // => \/-("1 done") 
+0

,似乎並沒有工作。 – ssanj

+0

它適合我。我已經用完整的工作示例更新了我的答案。 – danielnixon

+0

是的,它的工作原理!我之前嘗試過的時候肯定錯過了一些東西。謝謝。 – ssanj