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

Fold enumeration function #1139

Open
jakedipity opened this issue Nov 25, 2024 · 1 comment
Open

Fold enumeration function #1139

jakedipity opened this issue Nov 25, 2024 · 1 comment

Comments

@jakedipity
Copy link

Having a fold function like the rust's Iterator::fold would be a nice-to-have for compacting objects array into a single value.

Consider the contrived issue of trying to tally the total count of elements parsed out of a line

count(25) count(3) count(42) count(1);

This is currently possible but requires side effects to accomplish:

matches = parse_regex_all!(.message, r'count\((?<count>\d+)\)')
.count = 0
for_each(matches) -> |_index, value| {
  .count = .count + (to_int(value.count) ?? 0)
}

A fold function provides a slightly more terse way to accomplish this.

matches = parse_regex_all!(.message, r'count\((?<count>\d+)\)')
.count = fold(matches, 0) -> |accum, _index, value| {
  accum + (to_int(value.count) ?? 0)
}

I got ahead of myself and already started working on an implementation. Assuming you think this function is useful to include in the stdlib, the only thing I'm unsure of now is how to type the accumulator value of the closure.

  • The simplest answer is to treat it as Kind::ANY but this always requires type assertions and handling within the function.
  • My current implementation treats it as the same type as initial_value, with some small changes to the internals.
  • The ideal seems to be a union between the initial_value and closure return type - although this probably requires further changes to the internals
@pront
Copy link
Member

pront commented Nov 25, 2024

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

No branches or pull requests

2 participants