简体   繁体   English

Scalaz验证和ApplicativeBuilder限制

[英]Scalaz validation and ApplicativeBuilder limits

We're using scalaz validation trait in our project to validate HTTP parameters. 我们在项目中使用scalaz验证特性来验证HTTP参数。 The common case is taking few validated values and performing neccessary action only if all of them are valid, returning list of errors otherwise: 常见的情况是,只有在所有值都有效的情况下,只需要很少的验证值并执行必要的操作,否则返回错误列表:

(pavam1Val.liftFailNel |@|
 param2Val.liftFailNel |@|
 param3Val.liftFailNel) {
    getSomeResponse(_, _, _)
}

This works nice, until we have to use more than 8 parameters, because |@| 这很好用,直到我们必须使用8个以上的参数,因为| @ | operator constructs ApplicativeBuilder, which is limited to 8 arguments. operator构造ApplicativeBuilder,限制为8个参数。 Is there another way to perform such all-at-once validation, preferably keeping the code readable? 是否有其他方法可以执行此类一次性验证,最好是保持代码可读?

you want to use the <*> method, along with a single call to map (or if you prefer). 你想使用<*>方法,以及一次调用map (如果你愿意,可以使用 )。 You can keep using <*> indefinitely. 您可以无限期地继续使用<*>

scala> val param1Val = success[String, Int](7)                              
param1Val: scalaz.Validation[String,Int] = Success(7)

scala> val param2Val = failure[String, Int]("abc")                          
param2Val: scalaz.Validation[String,Int] = Failure(abc)

scala> val param3Val = success[String, Int](9)                              
param3Val: scalaz.Validation[String,Int] = Success(9)

scala> val r = param1Val <*> (param2Val <*> (param3Val map getSomeResponse))
r: scalaz.Validation[String,Int] = Failure(abc)

A couple more ways to do it: 还有几种方法可以做到:

  1. Lift the relevant function to Validation context, and then apply it to the values. 将相关函数提升到Validation上下文,然后将其应用于值。

     getSomeResponse.lift[({ type L[X] = Validation[Y, X] })#L] apply ( param1Val, param2Val, param3Val ) 
  2. Use monad comprehension. 使用monad理解。

     for { x1 <- param1Val x2 <- param2Val x3 <- param3Val } yield getSomeResponse(x1, x2, x3) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM