Skip to content

Commit

Permalink
Made imperative code more obviously imperative
Browse files Browse the repository at this point in the history
  • Loading branch information
npryce committed Oct 9, 2023
1 parent 0888b34 commit f087b24
Showing 1 changed file with 12 additions and 19 deletions.
31 changes: 12 additions & 19 deletions result4k/core/src/main/kotlin/dev/forkhandles/result4k/iterables.kt
Original file line number Diff line number Diff line change
Expand Up @@ -20,37 +20,30 @@ fun <T, E> Iterable<Result<T, E>>.partition(): Pair<List<T>, List<E>> {
}

// Traverse family of functions

fun <T, Tʹ, E> Iterable<T>.foldResult(
initial: Result<Tʹ, E>,
operation: (acc: Tʹ, T) -> Result<Tʹ, E>
): Result<Tʹ, E> =
fold(initial) { acc, el -> acc.flatMap { accVal -> operation(accVal, el) } }

fun <T, Tʹ, E> Iterable<T>.mapAllValues(f: (T) -> Result<Tʹ, E>): Result<List<Tʹ>, E> =
foldResult(Success(mutableListOf())) { acc, e ->
f(e).map { acc.add(it); acc }
}

fun <T, Tʹ, E> Sequence<T>.foldResult(
initial: Result<Tʹ, E>,
operation: (acc: Tʹ, T) -> Result<Tʹ, E>
): Result<Tʹ, E> {
val iter = iterator()

tailrec fun loop(acc: Result<Tʹ, E>): Result<Tʹ, E> =
if (!iter.hasNext()) acc
else when (acc) {
is Success -> loop(operation(acc.value, iter.next()))
is Failure -> acc
}
): Result<Tʹ, E> =
fold(initial) { acc, el -> acc.flatMap { accVal -> operation(accVal, el) } }

return loop(initial)
fun <T, Tʹ, E> Iterable<T>.mapAllValues(f: (T) -> Result<Tʹ, E>): Result<List<Tʹ>, E> {
return mutableListOf<Tʹ>()
.also { results -> forEach { e -> results.add(f(e).onFailure { return it }) } }
.let(::Success)
}

fun <T, Tʹ, E> Sequence<T>.mapAllValues(f: (T) -> Result<Tʹ, E>): Result<List<Tʹ>, E> =
foldResult(Success(mutableListOf())) { acc, e ->
f(e).map { acc.add(it); acc }
}
fun <T, Tʹ, E> Sequence<T>.mapAllValues(f: (T) -> Result<Tʹ, E>): Result<List<Tʹ>, E> {
return mutableListOf<Tʹ>()
.also { results -> forEach { e -> results.add(f(e).onFailure { return it }) } }
.let(::Success)
}

fun <T, E> Sequence<Result<T, E>>.allValues(): Result<List<T>, E> =
mapAllValues { it }

0 comments on commit f087b24

Please sign in to comment.