scala – 如何使用申请函数应用程序
发布时间:2020-12-16 18:14:31 所属栏目:安全 来源:网络整理
导读:我有以下验证逻辑: 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 vali
我有以下验证逻辑:
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,... vn) => ...)` * * `(f1 |@| f2 |@| ... |@| fn).tupled` is an alternative to `Apply[F].applyN(f1,fn)(TupleN.apply _)` * * Warning: each call to `|@|` leads to an allocation of wrapper object. For performance sensitive code,consider using * [[scalaz.Apply]]`#applyN` directly. */ 如何将validate函数转换为使用apply2? 解决方法
Validate的类型构造函数有两个参数,但Apply只能由arity one的类型构造函数参数化.你需要一个名为type lambda的特殊技巧,它允许我们讨论类型定义:
def validate(a : String) = Apply[({type λ[Int] = Validation[String,Int]})#λ].apply2(one(a),two(a)){_ + _} (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |