-
Notifications
You must be signed in to change notification settings - Fork 75
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
Conversation
Thanks for this. I like this idea a lot! I think we could simplify its implementation, as it shares a lot of structure with |
@michaelbull "Yes, I know that fold can be used to do the same thing, |
I'm not suggesting that |
@michaelbull That's a good idea. I've just edited it, please check it again. |
9133ba7
to
260d2c2
Compare
Hi @hoangchungk53qx1, apologies for taking so long to get back to you on this. The more I've studied this implementation, the more I am convinced that the Please can you let me know there's something I am missing with regards to this function in comparison to |
In functional programming, while operators are reusable, their meanings can vary. Additionally, the concept of Traversable should be clearly understood and distinguished from other ideas. |
The implementation of
public inline fun <V, E, U> Iterable<V>.mapResult(
transform: (V) -> Result<U, E>,
): Result<List<U>, E> {
val values = map { element ->
val transformed = transform(element)
when {
transformed.isOk -> transformed.value
else -> return transformed.asErr()
}
}
return Ok(values)
} Your public fun <V, E, U> Iterable<V>.traverse(
transform: (V) -> Result<U, E>
): Result<List<U>, E> {
val results = mutableListOf<U>()
for (item in this) {
val result = transform(item)
val element = when {
result.isOk -> result.value
else -> return Err(result.error)
}
results.add(element)
}
return Ok(results)
} |
Ohh, It seems that I haven't fully read mapResult, because I only gradually converted from Haskell. |
mapResult can do this, i will close this MR |
👍 |
This pull request introduces a new extension function, traverse, inspired by the traverse function in Haskell's Data.Traversable module.
Link : https://hackage.haskell.org/package/base-4.10.0.0/docs/Data-Traversable.html#t:Traversable
The goal is to provide a safe and declarative way to transform collections while handling potential errors gracefully.
functional programming, traverse allows us to apply a function that returns a Result (or any monadic type) to each element of a collection and collect the results into a single Result containing the transformed collection. If any transformation fails, the entire operation short-circuits, returning the first error encountered. This is particularly useful for scenarios where we need to ensure all transformations succeed or fail early on the first error.