如何使用申请功能申请
How to use Apply for Function Application
我有以下验证逻辑:
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
?
Validate
的类型构造函数有两个参数,但 Apply
只能由第一个类型构造函数参数化。您需要一个称为 type lambda 的特殊技巧,它允许我们柯里化类型定义:
def validate(a : String) = Apply[({type λ[Int] = Validation[String, Int]})#λ].apply2(one(a), two(a)){_ + _}
我有以下验证逻辑:
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
?
Validate
的类型构造函数有两个参数,但 Apply
只能由第一个类型构造函数参数化。您需要一个称为 type lambda 的特殊技巧,它允许我们柯里化类型定义:
def validate(a : String) = Apply[({type λ[Int] = Validation[String, Int]})#λ].apply2(one(a), two(a)){_ + _}