我有以下验证逻辑:
def one(a : String) : Validation[String, Int] =
if (a == "one") {
Success(1)
} else {
Failure("Not One")
}
def two(a : String) : Validation[String, Int] =
if (a == "two") {
Success(2)
} else {
Failure("Not Two")
}
def validate (a : String) = (one(a) |@| two(a)){_ + _}
根据Scalaz文档:
/**
* DSL for constructing Applicative expressions.
*
* `(f1 |@| f2 |@| ... |@| fn)((v1, v2, ... vn) => ...)` is an alternative to `Apply[F].applyN(f1, f2, ..., fn)((v1, v2, ... vn) => ...)`
*
* `(f1 |@| f2 |@| ... |@| fn).tupled` is an alternative to `Apply[F].applyN(f1, f2, ..., fn)(TupleN.apply _)`
*
* Warning: each call to `|@|` leads to an allocation of wrapper object. For performance sensitive code, consider using
* [[scalaz.Apply]]`#applyN` directly.
*/
如何将验证功能转换为使用apply2
?
答案 0 :(得分:4)
Validate
的类型构造函数有两个参数,但Apply
只能由arity one的类型构造函数参数化。你需要一个名为lambda的特殊技巧,它允许我们讨论类型定义:
def validate(a : String) = Apply[({type λ[Int] = Validation[String, Int]})#λ].apply2(one(a), two(a)){_ + _}