Skip to content

Implement traverse Inspired by Haskell for Safe Transformations #121

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -385,3 +385,20 @@ public inline fun <V, E, U : Any, C : MutableCollection<in U>> Iterable<V>.mapRe

return Ok(values)
}

/**
* Applies the given [transform] function to each element in this [Iterable<V>], collecting the results into a [Result<List<U>, E>].
* If all transformations succeed, returns an [Ok] containing a list of [U] values in the same order as the original [Iterable].
* If any transformation fails, immediately returns the first [Err]
* encountered and stops processing further elements.
*/
public inline fun <V, E, U> Iterable<V>.traverse(transform: (V) -> Result<U, E>): Result<List<U>, E> {
return fold(
initial = emptyList<U>(),
operation = { acc: List<U>, element: V ->
transform(element).map { value ->
acc + value
}
}
)
}
Original file line number Diff line number Diff line change
Expand Up @@ -199,4 +199,36 @@ class IterableTest {
)
}
}

class Traverse {
@Test
fun returnTraverseValueIfOk() {
val input = listOf(1, 2, 3)
val transform: (Int) -> Result<String, String> = { Ok(it.toString()) }
val result = input.traverse(transform)

assertEquals(Ok(listOf("1", "2", "3")), result)
}

@Test
fun returnsFirstErrorIfErr() {
val input = listOf(1, 2, 3)
val transform: (Int) -> Result<String, String> = {
if (it == 1) Err("Error at 1") else Ok(it.toString())
}
val result = input.traverse(transform)

assertEquals(Err("Error at 1"), result)
}

@Test
fun traverseWithEmptyListReturnsEmptyOkList() {
val input = emptyList<Int>()
val transform: (Int) -> Result<String, String> = { Ok(it.toString()) }
val result = input.traverse(transform)

assertEquals(Ok(emptyList()), result)
}

}
}
Loading