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
New function: Count number of occurences of each item in an iterator #467
Comments
If we decide to merge #465, this would be solved by |
I fail to see how let values = [0, 0, 0, 1, 1, 2];
let counts = values.into_iter().count_each();
assert_eq!(3, counts[0]);
assert_eq!(2, counts[1]);
assert_eq!(1, counts[2]); The |
You may have to use |
I'd say that your inability to figure out how to use the It would be easy enough to write this |
That's an interesting take. Actually, when I saw the first proposal of Still, we should possibly investigate whether we can make Would you agree that - if hypothetically possible - |
That other idea would be similar in complexity, so long as the documentation makes it clear that this method can be used (I'm not sure if I'd personally be able to figure out from the documentation in the PR that those methods are what I want to use to count distinct things in an iterator, if it had been already merged and I was staring at the documentation). Although, I'm not sure that approach would be any better for people's uses. I can't think of any use cases where you'd want |
Yes, I'd very much like to see a method like this in itertools! Something like this would do the trick: pub trait Itertools: Iterator {
...
fn foo(self) -> HashMap<Self::Item, usize>
where
Self: Sized,
Self::Item: Eq + Hash,
{
let mut counts = HashMap::new();
self.for_each(|elt| *counts.entry(elt).or_insert(0) += 1);
counts
}
...
} I don't know what the name ought to be; perhaps:
I think |
Author of #465 here. I agree with you that a separate function would be better, IMO because:
If your PR lands I'm in favour of removing |
468: Create counts method and tests for it r=jswrenn a=JarredAllen Creates the function described in #467 (I went with the name `counts`). It currently uses `for_each` and makes a `HashMap` manually because the PR for the `into_grouping_map` function is still being worked on, but this function could easily be changed to call it once that PR is merged, if desired. Co-authored-by: JarredAllen <jarredallen73@gmail.com>
It'd be nice if there could be a function in the
Itertools
trait which counts the number of times each element appears in the iterator and returns aHashMap
of that information (maybe namedcount_each
? I'm not too sure on the name).I recently had to do this in code that I was writing and was surprised that I couldn't find this functionality in here. I could add this myself pretty easily, if this is wanted (not sure how that process works as I'm new to this project), as I've just written it in my own code.
The text was updated successfully, but these errors were encountered: