Skip to content

Commit

Permalink
refactoring allValues() and mapAllValues()
Browse files Browse the repository at this point in the history
  • Loading branch information
dkandalov committed Oct 11, 2023
1 parent a03a43e commit 5ab7751
Showing 1 changed file with 8 additions and 15 deletions.
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
package dev.forkhandles.result4k


fun <T, E> Iterable<Result<T, E>>.allValues(): Result<List<T>, E> =
Success(map { r -> r.onFailure { return it } })
mapAllValues { it }

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

fun <T, E> Iterable<Result<T, E>>.anyValues(): List<T> =
filterIsInstance<Success<T>>().map { it.value }
Expand All @@ -19,8 +21,6 @@ fun <T, E> Iterable<Result<T, E>>.partition(): Pair<List<T>, List<E>> {
return Pair(oks, errs)
}

// Traverse family of functions

fun <T, Tʹ, E> Iterable<T>.foldResult(
initial: Result<Tʹ, E>,
operation: (acc: Tʹ, T) -> Result<Tʹ, E>
Expand All @@ -33,17 +33,10 @@ fun <T, Tʹ, E> Sequence<T>.foldResult(
): 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> {
return mutableListOf<Tʹ>()
.also { results -> forEach { e -> results.add(f(e).onFailure { return it }) } }
fun <T, Tʹ, E> Iterable<T>.mapAllValues(f: (T) -> Result<Tʹ, E>): Result<List<Tʹ>, E> =
map { e -> f(e).onFailure { return it } }
.let(::Success)
}

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 }) } }
fun <T, Tʹ, E> Sequence<T>.mapAllValues(f: (T) -> Result<Tʹ, E>): Result<List<Tʹ>, E> =
mapTo(mutableListOf()) { e -> 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 5ab7751

Please sign in to comment.