How can i convert a `List<Either<A,B>&gt...
# arrow
s
How can i convert a
List<Either<A,B>>
TO
Either<List<A>,List<B>>
OR
ValidaterNel<A,List<B>>
basically it iterates over either and collect both errors and success, •
.sequence
shortCircuits
which isnt wanted here*,* •
.traverse {}
is there but I thought there would a extension function for above as its a common useCase I guess, is there an extension for above ?
have builtSomething like this:
Copy code
fun <A, B> Iterable<Either<A, B>>.toValidatedNel(): ValidatedNel<A, List<B>> {
    return traverse(semigroup = Semigroup.nonEmptyList()) { it.toValidatedNel() }
}
s
This is your best bet, there is nothing out of the box for this in Arrow atm. We are unifying
Either
and
Validated
in Arrow 2.x.x, so this would be covered by that.
r
still on going but work is happening in this branch https://github.com/arrow-kt/arrow/pull/2778
s
have come up with below: Suggestions are welcome.
s
Hey @Shabinder Singh, I don’t think your observation is correct. It starts with an
acc = Valid(emptyList())
and then it runs
f
with the first element of the
Iterable
. If
val res = f(a)
returns
Invalid
it will check the state of
acc
and combine the results when needed. So for example
listOf(1).traverse { Invalid(it) }
it will start with
acc = Valid(emptyList<B>())
and then run
val res = Invalid(1)
. Since
res
is
Invalid
and
acc = Valid
it will return the
Invalid
case. Here are a property based test that verify this, https://github.com/arrow-kt/arrow/blob/96c774a08b1c86f369f075b4b8dd81a8904121d1/ar[…]ore/arrow-core/src/commonTest/kotlin/arrow/core/IterableTest.kt