我试着写了下面的验证函数,以便在遇到第一个错误后停止验证。其中three
函数的返回类型与其他函数不同。请问我该使用哪个单子变换器使得这段代码能够编译?
import scalaz._
import Scalaz._
import scala.concurrent.Future
import scala.concurrent.ExecutionContext.Implicits.global
def one(a : String): Disjunction[Int, String] =
a == "one" match {
case true => \/-("one")
case false => -\/(2)
}
def two(a : String): Disjunction[Int, String] =
a == "two" match {
case true => \/-("two")
case false => -\/(3)
}
def three(a : String): Future[Disjunction[Int, String]] =
Future (a == "three") map {
case true => \/-("three")
case false => -\/(4)
}
def validate(a : String) = for {
e1 <- one(a)
e2 <- two(a)
e3 <- EitherT(three(a))
} yield (e1 |+| e2 |+| e3)
编译错误:
Error:(27, 7) type mismatch;
found : scalaz.EitherT[scala.concurrent.Future,Int,String]
required: scalaz.\/[?,?]
e3 <- EitherT(three(a))
^
Error:(66, 7) type mismatch;
found : scalaz.EitherT[scala.concurrent.Future,Int,String]
required: scalaz.\/[?,?]
e3 <- EitherT(three(a))
^
one
和two
包装在Future
中,或者等待three
的结果? - Bruno GriederEitherT
单子变换器,第三个<-
语句返回的不是String
,而是整个Disjunction
,这可能不是你想要的(前两个访问了 disjunction 的String
部分)。 - Ende Neu