Skip to content

Commit

Permalink
Traverse family of functions for R4K (#46)
Browse files Browse the repository at this point in the history
* Traverse family of functions for R4K

Signed-off-by: Uberto Barbini <uberto.gama@gmail.com>

* Removed println and fixed formatting

Signed-off-by: Uberto Barbini <uberto.gama@gmail.com>

* renamed tests following conventions

Signed-off-by: Uberto Barbini <uberto.gama@gmail.com>

* renamed traverse to mapAllValues following conventions

Signed-off-by: Uberto Barbini <uberto.gama@gmail.com>

* Made imperative code more obviously imperative

---------

Signed-off-by: Uberto Barbini <uberto.gama@gmail.com>
Co-authored-by: Nat Pryce <sw@natpryce.com>
  • Loading branch information
uberto and npryce authored Oct 9, 2023
1 parent a1e3931 commit a03a43e
Show file tree
Hide file tree
Showing 2 changed files with 137 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -18,3 +18,32 @@ 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>
): Result<Tʹ, E> =
fold(initial) { acc, el -> acc.flatMap { accVal -> operation(accVal, el) } }

fun <T, Tʹ, E> Sequence<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> {
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> {
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 }
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package dev.forkhandles.result4k

import org.junit.jupiter.api.Test
import kotlin.random.Random
import kotlin.test.assertEquals

class AllValuesTests {
Expand Down Expand Up @@ -35,3 +36,110 @@ class PartitionTests {
listOf(Failure("bad"), Failure("also bad")).partition())
}
}

private fun randomPositiveInt() = Random.nextInt(1, 100)

private fun generateRandomList(): List<Int> =
listOf(
randomPositiveInt(),
randomPositiveInt(),
randomPositiveInt(),
randomPositiveInt(),
randomPositiveInt()
)
class TraverseIterableTests {
@Test
fun `returns the first failure or the folded iterable as success`() {
val list = generateRandomList()
assertEquals(Success(list.sum()),
list.foldResult(Success(0)) { acc: Int, i: Int -> Success(acc + i) })
}

@Test
fun `returns the first failure or the mapping of iterable as success`() {
val list = generateRandomList()
assertEquals(Success(list.map { it * 2 }),
list.mapAllValues { i -> Success(i * 2) })
}

@Test
fun `returns the first failure or the iterable as success`() {
val list = generateRandomList().map { Success(it) }
assertEquals(Success(list.map { it.value }),
list.allValues())
}

@Test
fun `failure is returned if the folding operation fails`() {
val list = generateRandomList()
fun failingOperation(a: Int, b: Int) = Failure("Test error")

assertEquals(Failure("Test error"),
list.foldResult(Success(100), ::failingOperation))
}

@Test
fun `failure is returned if the mapping operation fails`() {
val list = generateRandomList()
val failingFunction: (Int) -> Result<Int, String> = { _ -> Failure("Test error") }
assertEquals(Failure("Test error"),
list.mapAllValues(failingFunction))
}

@Test
fun `failure is returned if the iterable contained a failure`() {
val list = listOf(Success(randomPositiveInt()), Failure("Test error"))
assertEquals(Failure("Test error"),
list.allValues())
}
}

class TraverseSequenceTests {

@Test
fun `returns the first failure or the folded sequence as success`() {
val list = generateRandomList()
val sequence = list.asSequence()
assertEquals(Success(list.sum()),
sequence.foldResult(Success(0)) { acc, i -> Success(acc + i) })
}

@Test
fun `returns the first failure or the mapping of sequence as success`() {
val list = generateRandomList()
val sequence = list.asSequence()
assertEquals(Success(list.map { it * 2 }),
sequence.mapAllValues { i -> Success(i * 2) })
}

@Test
fun `returns the first failure or the mapped sequence as success`() {
val list = generateRandomList()
val sequence = list.map { Success(it) }.asSequence()
assertEquals(Success(list),
sequence.allValues())
}

@Test
fun `failure is returned if the folding operation fails`() {
val sequence = generateSequence { randomPositiveInt() }.take(5)
val failingOperation: (Int, Int) -> Result<Int, String> = { _, _ -> Failure("Test error") }
assertEquals(Failure("Test error"),
sequence.foldResult(Success(0), failingOperation))
}

@Test
fun `failure is returned if the mapping operation fails`() {
val sequence = generateSequence { randomPositiveInt() }.take(5)
val failingFunction: (Int) -> Result<Int, String> = { _ -> Failure("Test error") }
assertEquals(Failure("Test error"),
sequence.mapAllValues(failingFunction))
}

@Test
fun `failure is returned if the sequence contained a failure`() {
val sequence = generateSequence { Success(randomPositiveInt()) }.take(5) + sequenceOf(Failure("Test error"))
assertEquals(Failure("Test error"),
sequence.allValues())
}
}

0 comments on commit a03a43e

Please sign in to comment.