简体   繁体   English

Scalaz使用带有验证和验证列表的应用生成器

[英]Scalaz use applicative builder with validations and a list of validations

I'm working with Scalaz validations and I've run into a situation like this (note this is heavily simplified from my actual code, but the idea is the same) 我正在使用Scalaz验证,并且遇到了这样的情况(请注意,这与我的实际代码相比已大大简化,但是想法是相同的)

Given: 鉴于:

case class Foo(bar: Int)

val x1: Validation[String, Foo] = Foo(1).success
val x2: Validation[String, Foo] = Foo(2).success
val x3: Validation[String, Foo] = Foo(3).success

val l1 = List(x1, x2)

I would like to be able to do something along the lines this: 我希望能够做到这一点:

(x3 |@| l1) { (x1, x2, x3) => /*do something with all of my Foo's*/ } 

Of course if there were any errors, either in the list or outside of the list I'd like them to accumulate as they normally would. 当然,如果有任何错误,无论是在列表中还是列表外,我都希望它们像往常一样积累。

I know the above syntax does not work, but any advice on how to achieve the result I'm looking for would be appreciated. 我知道上面的语法不起作用,但是任何有关如何实现我要寻找的结果的建议都将不胜感激。

If you have a List[F[A]] and F has an applicative functor instance, you can turn the list inside out in effect with sequenceU to get a F[List[A]] : 如果您有一个List[F[A]]并且F有一个应用函子实例,则可以使用sequenceU将列表内外有效,以获得F[List[A]]

scala> l1.sequenceU
res0: scalaz.Validation[String,List[Foo]] = Success(List(Foo(1), Foo(2)))

Or: 要么:

scala> (x3 |@| l1.sequenceU) {
  case (third, rest) => // do something with the values
}

It's also worth noting that if you find yourself writing things of the xs.map(f).sequenceU , you can use xs.traverseU(f) instead—it's exactly equivalent except you don't build an intermediate list. 还值得注意的是,如果您发现自己编写了xs.map(f).sequenceU ,则可以改用xs.traverseU(f) -完全等效,只是不构建中间列表。

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

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