Mike
04/04/2021, 12:31 PMtraversEither
on a List vs a Nel or am I using it wrong?
If I run below Kotest code, The Nel one ends up with 4 elements (the head gets repeated at the end of the list)
"Test traverseEither on list" {
val t = listOf(1, 2, 3).traverseEither { i ->
i.right()
}
val list = (t as Either.Right<List<String>>).value
list shouldHaveSize 3 // true [1, 2, 3]
}
"Test traversEither on NEL" {
val fromList = Nel.fromListUnsafe(listOf(1, 2, 3))
val t = fromList.traverseEither { it.right() }
val list = (t as Either.Right<List<String>>).value
list shouldHaveSize 3 // false [1, 2, 3, 1]
}
aballano
04/04/2021, 12:50 PMaballano
04/04/2021, 12:52 PMMike
04/04/2021, 3:31 PMYoussef Shoaib [MOD]
04/04/2021, 3:48 PMinline fun <E, A, B> NonEmptyList<A>.traverseEither(f: (A) -> Either<E, B>): Either<E, NonEmptyList<B>> =
foldRight(f(head).map(::nonEmptyListOf)) { a, acc ->
when (val res = f(a)) {
is Right -> acc.map { bs -> nonEmptyListOf(res.value) + bs }
is Left -> res
}
}
`f(head).map(::nonEmptyListOf)`This part right here causes it to first go through the head, then go through every element from first to last (including the head again). I'm not entirely sure what the solution would be here, except maybe doing tail.foldRight(...){...}
but I'm not sure if that'll produce exactly the same resultaballano
04/04/2021, 3:49 PMaballano
04/04/2021, 3:53 PMYoussef Shoaib [MOD]
04/04/2021, 3:54 PMYoussef Shoaib [MOD]
04/04/2021, 5:47 PMaballano
04/04/2021, 5:48 PMYoussef Shoaib [MOD]
04/04/2021, 5:49 PM