Is it possible to use Scalaz' traverse
and traverseU
with Either
instead of Option
?
For the following code:
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")
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.
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))
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))