以下是the Scala with Cats book的一个例子:
object Ex {
import cats.data.Validated
type FormData = Map[String, String]
type FailFast[A] = Either[List[String], A]
def getValue(name: String)(data: FormData): FailFast[String] =
data.get(name).toRight(List(s"$name field not specified"))
type NumFmtExn = NumberFormatException
import cats.syntax.either._ // for catchOnly
def parseInt(name: String)(data: String): FailFast[Int] =
Either.catchOnly[NumFmtExn](data.toInt).leftMap(_ => List(s"$name must be an integer"))
def nonBlank(name: String)(data: String): FailFast[String] =
Right(data).ensure(List(s"$name cannot be blank"))(_.nonEmpty)
def nonNegative(name: String)(data: Int): FailFast[Int] =
Right(data).ensure(List(s"$name must be non-negative"))(_ >= 0)
def readName(data: FormData): FailFast[String] =
getValue("name")(data).
flatMap(nonBlank("name"))
def readAge(data: FormData): FailFast[Int] =
getValue("age")(data).
flatMap(nonBlank("age")).
flatMap(parseInt("age")).
flatMap(nonNegative("age"))
case class User(name: String, age: Int)
type FailSlow[A] = Validated[List[String], A]
import cats.instances.list._ // for Semigroupal
import cats.syntax.apply._ // for mapN
def readUser(data: FormData): FailSlow[User] =
(
readName(data).toValidated,
readAge(data).toValidated
).mapN(User.apply)
一些注意事项:每个原始验证函数:nonBlank
,nonNegative
,getValue
返回所谓的FailFast类型,它是monadic,不适用。
有两个函数readName
和readAge
,它们使用前面的组合,并且本质上也是FailFast。
readUser
恰恰相反,失败缓慢。为了实现它,readName
和readAge
的结果被转换为Validated并通过所谓的“语法”组成
假设我有另一个验证函数,它接受名称和年龄,由readName
和readAge
验证。对于国际事务:
//fake implementation:
def validBoth(name:String, age:Int):FailSlow[User] =
Validated.valid[List[String], User](User(name,age))
如何用validBoth
和readAge撰写readName
?快速失败很简单,因为我使用for-comrehension
并可以访问readName
和readAge
的结果:
for {
n <- readName...
i <- readAge...
t <- validBoth(n,i)
} yield t
但是如何为faillow获得相同的结果?
编辑可能还不够清楚,有这些功能。这是一个真实的用例。有一个函数,类似于readName / readAge,以类似的方式验证日期。我想创建一个验证功能,它接受2个日期,以确保一个日期接着另一个日期。日期来自String。下面是一个示例,它对于FailFast来说会是什么样子,这不是这个上下文中的最佳选择:
def oneAfterAnother(dateBefore:Date, dateAfter:Date): FailFast[Tuple2[Date,Date]] =
Right((dateBefore, dateAfter))
.ensure(List(s"$dateAfter date cannot be before $dateBefore"))(t => t._1.before(t._2))
for {
dateBefore <- readDate...
dateAfter <- readDate...
t <- oneDateAfterAnother(dateBefore,dateAfter)
} yield t
我的目的是以适用的方式积累可能的日期错误。据说这本书,p。 157:
我们不能flatMap因为Validated不是monad。但是,Cats确实为flatMap提供了一个名为andThen的替身。 andThen的类型签名与flatMap的类型签名相同,但它具有不同的名称,因为它不是关于monad法则的合法实现:
32.valid.andThen { a =>
10.valid.map { b =>
a + b
}
}
好吧,我尝试重用这个解决方案,基于andThen
,但结果有monadic,但不是应用效果:
def oneDateAfterAnotherFailSlow(dateBefore:String, dateAfter:String)
(map: Map[String, String])(format: SimpleDateFormat)
: FailSlow[Tuple2[Date, Date]] =
readDate(dateBefore)(map)(format).toValidated.andThen { before =>
readDate(dateAfter)(map)(format).toValidated.andThen { after =>
oneAfterAnother(before,after).toValidated
}
}
我最终可以使用以下代码编写它:
import cats.syntax.either._
import cats.instances.list._ // for Semigroupal
def oneDateAfterAnotherFailSlow(dateBefore:String, dateAfter:String)
(map: Map[String, String])(format: SimpleDateFormat)
: FailFast[Tuple2[Date, Date]] =
for {
t <-Semigroupal[FailSlow].product(
readDate(dateBefore)(map)(format).toValidated,
readDate(dateAfter)(map)(format).toValidated
).toEither
r <- oneAfterAnother(t._1, t._2)
} yield r
这个想法是,应用字符串的第一次验证,以确保日期是正确的。它们通过Validated(FailSlow)累积。然后使用fail-fast,因为如果任何日期错误且无法解析,继续并将它们作为日期进行比较是没有意义的。
它通过了我的测试用例。
如果您能提供另一种更优雅的解决方案,请随时欢迎!
也许代码在这里是不言自明的:
/** Edited for the new question. */
import cats.data.Validated
import cats.instances.list._ // for Semigroup
import cats.syntax.apply._ // for tupled
import cats.syntax.either._ // for toValidated
type FailFast[A] = Either[List[String], A]
type FailSlow[A] = Validated[List[String], A]
type Date = ???
type SimpleDateFormat = ???
def readDate(date: String)
(map: Map[String, String])
(format: SimpleDateFormat): FailFast[Date] = ???
def oneDateAfterAnotherFailSlow(dateBefore: String, dateAfter: String)
(map: Map[String, String])
(format: SimpleDateFormat): FailSlow[(Date, Date)] =
(
readDate(dateBefore)(map)(format).toValidated,
readDate(dateAfter)(map)(format).toValidated
).tupled.ensure(List(s"$dateAfter date cannot be before $dateBefore"))(t => t._1.before(t._2))
Applicatives的东西是你不应该(并且如果使用abastraction不能)使用flatMap
,因为那将具有顺序语义(在这种情况下FailFast
行为)。
因此,您需要使用它们提供的抽象,通常mapN
调用具有所有参数的函数(如果它们全部有效或tupled
创建元组)。
正如文档所述,andThen
应该用于你希望Validated作为Monad工作的地方而不是一个。
它只是方便,但如果你想要FailSlow
语义,你不应该使用它。
“这个函数类似于在Flat上的flatMap。它不叫flatMap,因为通过Cats约定,flatMap是一个与ap一致的monadic绑定。这个方法与ap(或其他基于Apply的方法)不一致,因为它有“失败快速”行为,而不是累积验证失败“。