Heyo, Is there a built in method to iterate over t...
# arrow
m
Heyo, Is there a built in method to iterate over the list and collect all failures from all items of the iterable?
traverse
seems to short circuit on the first failure.
I created below helper function, but wondering if I could achieve it with built it capabilities:
Copy code
fun <A, B> Iterable<B>.traverseAll(f: (B) -> Either<A, B>): Either<List<A>, List<B>> {
    val lefts: MutableList<A> = mutableListOf()
    val rights: MutableList<B> = mutableListOf()

    forEach { f(it).fold(lefts::add, rights::add) }

    return conditionally(
        test = lefts.isEmpty(),
        ifTrue = { rights },
        ifFalse = { lefts }
    )
}
q
If you have a
List<B>
and one function of type
(B) -> Either<A, B>
and you want to build
Either<A, List<B>>
accumulating the errors, You should think about Semigroup, So I think you can take a look at
traverse(Semigroup, B -> Validated<A, B>) or parTraverseValidated()
, Here a really good example https://www.47deg.com/blog/functional-domain-modeling-part-2
s
You can also use
Validated<NonEmptyList<E>, A>
and it will return
Validated<NonEmptyList<E>, List<A>>
from
traverse
and there will be no need to pass
Semigroup
. It uses
Semigroup
for
NonEmptyList
by default which is
{ listA, listB -> listA + listB }
so concatenation of the errors lists.
m
Sounds good. Wondering if is semantically correct or not when you process list of items which might have side effects.
s
typically in arrow we use
suspend
for functions with side effects.... so you can use Validated + suspend functions