Skip to content
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

Short-circuiting version of fold_left #1997

Closed
yannham opened this issue Jul 17, 2024 · 0 comments · Fixed by #2000
Closed

Short-circuiting version of fold_left #1997

yannham opened this issue Jul 17, 2024 · 0 comments · Fixed by #2000

Comments

@yannham
Copy link
Member

yannham commented Jul 17, 2024

Is your feature request related to a problem? Please describe.

fold_left is a useful combinator, and the one most often used for general iteration in functional programming (preferred over fold_right). However, as opposed to fold_right, it's not short-circuiting. For example, here is an excerpt of the implementation of std.contract.Sequence:

std.array.fold_left
  (
    fun acc Contract =>
      acc
      |> match {
        'Ok value =>
          std.contract.apply_as_custom Contract label value,
        # if we encountered an error at some point in the pipeline, we
        # just forward it from this point
        error => error
      }
  )
  ('Ok value)
  contracts

The idea is that we want apply the contracts from the given contracts list as long as they don't return an error, but stop at the first error. But we have to manually match on the accumulator and propagate the short-circuiting case all-along (error => error), which is a bit clumsy. This isn't the only place where this takes place.

Describe the solution you'd like

Add a function in the stdlib that would have a signature like:

try_fold_left: forall a b c. (a  -> c -> Result a b) -> a -> Array c -> Result a b

Where Result a b := [| 'Ok a, 'Error b |] (or something different, like Some/None, Continue/Stop, etc.). Whether it would be just sugar for the previous example, or it would use a special primop to actually be short-circuiting is an important question but even just a helper function to avoid the propagate-the-error boilerplate would be useful.

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

Successfully merging a pull request may close this issue.

1 participant