简体   繁体   English

scalaz 验证和列表单子

[英]scalaz validation and list monad

I am trying to come up with something similar to the following:我正在尝试提出类似于以下内容的内容:

val s: Validation[String, Int] = 1.success
def s2(i: Int): Validation[String, Int] = i.success

val result = for {
  i <- s
  j <- List(1, 2)
  k <- s2(j)
} yield "fine";

The above code does not compile and I understand, syntactically it does not make sense.上面的代码无法编译,我理解,在语法上它没有意义。

I am trying to execute a list of validations in a monadic way.我正在尝试以单子方式执行验证列表。 How do I achieve that?我该如何做到这一点?

If you have a list of validations of A , you can turn it into a validation of lists of A using sequence :如果您有A的验证列表,则可以使用sequence将其转换为A列表的验证:

List(1, 2).map(s2).sequence[({type l[a]=Validation[String, a]})#l, Int] 

(if I understand the question correctly). (如果我正确理解了这个问题)。 So you get所以你得到

val result = for {
  i <- s
  k <- List(1, 2).map(s2).sequence[({type l[a]=Validation[String, a]})#l, Int] 
} yield "fine"

You seem to be using validation for the side effect.您似乎正在使用验证来解决副作用。 This is not what its ment for.这不是它的目的。 You use the return values in functional programming.您在函数式编程中使用返回值。

Validation in a for comprehension continues with on success, but breaks of at a failure and returns the failure.对于理解的验证在成功时继续进行,但在失败时中断并返回失败。

scala> def g(i: Int): Validation[String, Int] = { 
          println(i); if(i % 2 == 0) i.success else "odd".fail 
       }
g: (i: Int)scalaz.Validation[String,Int]

scala> val result = for {
     |   i <- g(1)
     |   j <- g(2)
     | } yield (i,j)
1
result: scalaz.Validation[String,(Int, Int)] = Failure(odd)

scala> val result = for {
     |   i <- g(2)
     |   j <- g(1)
     | } yield (i,j)
2
1
result: scalaz.Validation[String,(Int, Int)] = Failure(odd)


scala> val result = for {
     |   i <- g(2)
     |   j <- g(2)
     | } yield (i,j)
2
2
result: scalaz.Validation[String,(Int, Int)] = Success((2,2))


scala> val result = for {
     |   i <- g(1)
     |   j <- g(1)
     | } yield (i,j)
1
result: scalaz.Validation[String,(Int, Int)] = Failure(odd)

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

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