本文介绍了如何使用Scalaz的traverse和traverseU与Either的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以将 Scalaz 的 traversetraverseUEither 一起使用,而不是 Option?

Is it possible to use Scalaz' traverse and traverseU with Either instead of Option?

对于以下代码:

val list = List(1, 2, 3)

def f(i: Int): Either[Int, String] =
  if (i > 2) Left(i)
  else Right("must be lower than 3")

我想用 f 遍历 list 并返回第一个 Right(msg) 如果有一个或多个失败,或者 Left(list) 如果一切顺利.

I want to traverse list with f and either return the first Right(msg) if there is one or more failure, or Left(list) if everything went right.

推荐答案

您是否有任何理由不使用 scalaz 的 ValidationNonEmptyList?

Is there any reason why you're not using Validation and NonEmptyList by scalaz?

你可以轻松地做类似的事情

You can easily do something like

def f(i: Int) =
  if (i > 2) i.successNel
  else "something wrong".failureNel

List(1, 2, 3).traverseU(f) // Failure(NonEmptyList(something wrong, something wrong))
List(3, 4, 5).traverseU(f) // Success(List(3, 4, 5))

如果你想在第一个错误时失败,你可以使用 \/,也就是 Either 的 scalaz 版本,它与 scala.Either 同构 但偏右

If you instead want to fail on the first error, you can use \/, aka the scalaz version of Either which is isomorphic to scala.Either but right-biased

def f(i: Int) =
  if (i > 2) \/-(i)
  else -\/("something wrong")

List(1, 2, 3).traverseU(f) // Failure(something wrong)
List(3, 4, 5).traverseU(f) // Success(List(3, 4, 5))

这篇关于如何使用Scalaz的traverse和traverseU与Either的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-30 08:43