vectordotdev / vrl

Vector Remap Language
Mozilla Public License 2.0
138 stars 69 forks source link

Fold enumeration function #1139

Open jakedipity opened 3 days ago

jakedipity commented 3 days ago

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.

pront commented 3 days ago

Thanks @jakedipity!

https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.fold

This sounds good. Similar to https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.fold.