diff --git a/result4k/core/src/main/kotlin/dev/forkhandles/result4k/iterables.kt b/result4k/core/src/main/kotlin/dev/forkhandles/result4k/iterables.kt index 9e894dd..bb59b26 100644 --- a/result4k/core/src/main/kotlin/dev/forkhandles/result4k/iterables.kt +++ b/result4k/core/src/main/kotlin/dev/forkhandles/result4k/iterables.kt @@ -20,37 +20,30 @@ fun Iterable>.partition(): Pair, List> { } // Traverse family of functions + fun Iterable.foldResult( initial: Result, operation: (acc: Tʹ, T) -> Result ): Result = fold(initial) { acc, el -> acc.flatMap { accVal -> operation(accVal, el) } } -fun Iterable.mapAllValues(f: (T) -> Result): Result, E> = - foldResult(Success(mutableListOf())) { acc, e -> - f(e).map { acc.add(it); acc } - } - fun Sequence.foldResult( initial: Result, operation: (acc: Tʹ, T) -> Result -): Result { - val iter = iterator() - - tailrec fun loop(acc: Result): Result = - if (!iter.hasNext()) acc - else when (acc) { - is Success -> loop(operation(acc.value, iter.next())) - is Failure -> acc - } +): Result = + fold(initial) { acc, el -> acc.flatMap { accVal -> operation(accVal, el) } } - return loop(initial) +fun Iterable.mapAllValues(f: (T) -> Result): Result, E> { + return mutableListOf() + .also { results -> forEach { e -> results.add(f(e).onFailure { return it }) } } + .let(::Success) } -fun Sequence.mapAllValues(f: (T) -> Result): Result, E> = - foldResult(Success(mutableListOf())) { acc, e -> - f(e).map { acc.add(it); acc } - } +fun Sequence.mapAllValues(f: (T) -> Result): Result, E> { + return mutableListOf() + .also { results -> forEach { e -> results.add(f(e).onFailure { return it }) } } + .let(::Success) +} fun Sequence>.allValues(): Result, E> = mapAllValues { it }