I wanted to a have the following functions that operate on f64 iterators
sum, avg, min, max
I am using rust-postgres to get a large number of rows out of the db and then using itertools::group_by
to give me a group of f64 series to perform those functions on. I want the particular function to be chosen before hand.
so ideally (The following is not tested) I want something like
let my_aggregation = get_aggregation_fn(Aggregate::SUM);
let data = rows.into_iter().map( |row| (row.get(0), row.get(1), row.get(2)))
.group_by(|t| (t.1, BmosConnection::floor_by_granularity(t.0, time_granularity)))
.map(|key, values| my_aggregation(values))
I do this instead of in Postgres because for large amounts of data it is much faster.
I also have a diff aggregation that requires getting all the data from postgres first so have to use this method.
I think you can work with closures. Either specify them inline/around the place you're going to invoke them, or you can return one (instead of a fn pointer). Given impl Trait is about to land, you'll be able to write the following (as an example) in stable:
let aggregate_fn = get_aggregation_fn(aggregate);
| ------------ ^^^^^^^^^^^^^^^^^^ cannot infer type for `I`
| |
| consider giving `aggregate_fn` a type
Gut feeling is that this is because of the lifetime used for get_agg. The compiler can't use a lifetime that begins afterget_agg gets run, and the lifetime has to support v.iter(), so v must exist before get_agg is called so that the borrow can retroactively extend backward to before get_agg is called.
As @DanielKeep said, the created closure creates a scope, 'a, for which the eventual borrow (when the closure is called) must be valid. This requires the f64s to be created prior to where the closure is created.
There’s no real need to have the aggregation functions working on f64 references - they should work on iterators that return f64 values, which removes the scope issue. If you have iterator iter that returns &f64, then iter.cloned() gives you an iterator that returns f64 values and this is of course a cheap transformation.