-
Notifications
You must be signed in to change notification settings - Fork 321
Add reductions() #147
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
Comments
Note that as suggested above I'm using a variant where the first element of the reductions() iterator will match the first element of the original iterator. Closure has another variant which allows you to specify an initial element, so that it will be the first element of the returned iterator instead. Edit: Python calls this function accumulate, and defaults it to computing the cumsum over the standard addition operator. This name probably fits Rust better than "reductions". |
It's similar to scan |
@bluss You're right, I have missed that function. This does seem to be easy to implement on top of scan(). Sorry for the noise! Edit: The ergonomics of scan() are not great if the reduction function has no identity element: iter.scan(None, |mut st, item| {
*st = Some(match *st {
Some(st_inner) => some_function(st_inner, item),
None => item
});
*st
})
// vs
iter.accumulate(some_function) |
Unless I missed it, there doesn't seem to currently exist a function to get an iterator of the intermediate values of a reduction function. Here is an example of how this can be used to easily create a cumulative sum iterator:
For me this use-case up when I needed a cumulative sum over an addition operator without inverse, to optimize sums of certain structure.
Does this seem like something that could be part of this library? (The name "reductions" is not great, as rust uses "fold" instead of "reduce", there's probably some other term for this.)
I came up with the following implementation for my own use, though me being new to Rust it likely does everything wrong:
The text was updated successfully, but these errors were encountered: