gpt4 book ai didi

scala - 如何使用申请功能申请

转载 作者:行者123 更新时间:2023-12-04 16:49:29 26 4
gpt4 key购买 nike

我有以下验证逻辑:

  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 的特殊技巧,它允许我们对类型定义进行柯里化(Currying):

def validate(a : String) = Apply[({type λ[Int] = Validation[String, Int]})#λ].apply2(one(a), two(a)){_  + _}

关于scala - 如何使用申请功能申请,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42315019/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com