如何编写返回 Validation 的函数?

2024-04-30

这是我之前的后续question https://stackoverflow.com/questions/30527740/composing-validating-functions-in-scala

假设我有两个验证函数,如果输入有效则返回输入,如果无效则返回错误消息。

type Status[A] = ValidationNel[String, A]

val isPositive: Int => Status[Int] = 
  x => if (x > 0) x.success else s"$x not positive".failureNel

val isEven: Int => Status[Int] = 
  x => if (x % 2 == 0) x.success else s"$x not even".failureNel

还假设我需要验证一个实例case class X:

case class X(x1: Int, // should be positive 
             x2: Int) // should be even

更具体地说,我需要一个函数checkX: X => Status[X]。此外,我想写checkX as a 作品 of isPositive and isEven.

val checkX: X => Status[X] =
  ({x => isPositive(x.x1)} |@| {x => isEven(x.x2)}) ((X.apply _).lift[Status])

是否有意义 ?
你会怎么写checkX as a 作品 of isPositive and isEven?


有很多方法可以写这个,但我喜欢以下:

val checkX: X => Status[X] = x => isPositive(x.x1).tuple(isEven(x.x2)).as(x)

Or:

val checkX: X => Status[X] =
  x => isPositive(x.x1) *> isEven(x.x2) *> x.point[Status]

关键点是您只想针对其“效果”运行这两个验证,然后在新上下文中返回原始值。正如您自己的实现所示,这是一个完全合法的应用程序操作。有一些稍微好一点的方法来编写它。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何编写返回 Validation 的函数? 的相关文章

随机推荐