处理 Scalaz6 验证列表 [英] Processing a list of Scalaz6 Validation

查看:35
本文介绍了处理 Scalaz6 验证列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一种惯用的方法来处理 Scalaz6 中的验证集合?

Is there an idiomatic way to handle a collection of Validation in Scalaz6?

val results:Seq[Validation[A,B]]
val exceptions = results.collect{case Failure(exception)=>exception}
exceptions.foreach{logger.error("Error when starting up ccxy gottware",_)}
val success = results.collect{case Success(data)=>data}
success.foreach {data => data.push}
if (exceptions.isEmpty)
   containers.foreach( _.start())

我可以考虑在循环结果时使用折叠,但最终测试呢?

I could think of using a fold when looping on results, but what about the final test?

推荐答案

处理验证列表的常用方法是使用 sequence 将列表转换为 Validation[A, List[B]],如果在此过程中出现任何错误,它将为空(即 Failure).

The usual way to work with a list of validations is to use sequence to turn the list into a Validation[A, List[B]], which will be be empty (i.e., a Failure) if there were any errors along the way.

Validation 进行排序会在左侧类型的半群中累积错误(与 Either 相反,后者会立即失败).这就是为什么您经常看到使用 ValidationNEL(其中 NEL 代表 NonEmptyList)而不是简单的 Validation.例如,如果您有以下结果类型:

Sequencing a Validation accumulates errors (as opposed to Either, which fails immediately) in the semigroup of the left-hand type. This is why you often see ValidationNEL (where the NEL stands for NonEmptyList) used instead of simply Validation. So for example if you have this result type:

import scalaz._, Scalaz._

type ExceptionsOr[A] = ValidationNEL[Exception, A]

还有一些结果:

val results: Seq[ExceptionsOr[Int]] = Seq(
  "13".parseInt.liftFailNel, "42".parseInt.liftFailNel
)

测序将为您提供以下信息:

Sequencing will give you the following:

scala> results.sequence
res0: ExceptionsOr[Seq[Int]] = Success(List(13, 42))

另一方面,如果我们有一些这样的错误:

If we had some errors like this, on the other hand:

val results: Seq[ExceptionsOr[Int]] = Seq(
  "13".parseInt.liftFailNel, "a".parseInt.liftFailNel, "b".parseInt.liftFailNel
)

我们最终会遇到 Failure(请注意,我已重新格式化输出以使其在此处清晰易读):

We'd end up with a Failure (note that I've reformatted the output to make it legible here):

scala> results.sequence
res1: ExceptionsOr[Seq[Int]] = Failure(
  NonEmptyList(
    java.lang.NumberFormatException: For input string: "a",
    java.lang.NumberFormatException: For input string: "b"
  )
)

所以在你的情况下你会写这样的东西:

So in your case you'd write something like this:

val results: Seq[ValidationNEL[A, B]]

results.sequence match {
  case Success(xs) => xs.foreach(_.push); containers.foreach(_.start())
  case Failure(exceptions) => exceptions.foreach(
    logger.error("Error when starting up ccxy gottware", _)
  )
}

查看我的回答这里此处 了解有关 sequenceValidation 的更多详细信息.

See my answers here and here for more detail about sequence and about Validation more generally.

这篇关于处理 Scalaz6 验证列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆