【发布时间】:2017-02-17 05:41:17
【问题描述】:
我正在尝试编写下面的验证函数,以便在遇到第一个错误后停止验证。 three 的返回类型与其他函数不同。我使用哪个 monad 转换器来编译这段代码?
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或Awaitthree的结果中? -
你想看看
EitherTmonad 转换器,你的第三个<-没有返回String,它给了你整个Disjunction,这可能不是你想要的(前两个访问析取的String部分)。 -
@EndeNeu 我尝试了 EitherT 但仍然出现编译错误。请参阅更新的问题以及编译错误。我之前使用过 DisjunctionT(它只是 EitherT 的包装器),结果相同。
标签: scala monads scalaz monad-transformers