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

Conversation

hoangchungk53qx1
Copy link
Contributor

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.

@michaelbull
Copy link
Owner

michaelbull commented Apr 6, 2025

Thanks for this. I like this idea a lot!

I think we could simplify its implementation, as it shares a lot of structure with fold. It looks to me like traverse could call fold with list::add as the second argument.

@hoangchungk53qx1
Copy link
Contributor Author

@michaelbull "Yes, I know that fold can be used to do the same thing,
but I want to write an operator that is more expressive in other functional languages."

@michaelbull
Copy link
Owner

I'm not suggesting that fold does the same thing, just that its implementation is largely shared between fold and traverse, so the new traverse function could call fold in its implementation to avoid duplication.

@hoangchungk53qx1
Copy link
Contributor Author

@michaelbull That's a good idea. I've just edited it, please check it again.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants