-
Notifications
You must be signed in to change notification settings - Fork 3.5k
add Enum.frequencies and Enum.frequencies_by #9425
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
Conversation
@QWYNG How about using reduce and implement only Here is my proposition: defmodule Example do
@spec frequencies_by(Enum.t(), (Enum.element() -> any)) :: map
def frequencies_by(enumerable, key_fun \\ fn x -> x end) when is_function(key_fun) do
Enum.reduce(enumerable, %{}, fn entry, acc ->
key = key_fun.(entry)
Map.update(acc, key, 1, &(&1 + 1))
end)
end
end |
Yes, we should go with @Eiji7 proposal, as it is quite more efficient. :) |
@Eiji7 @josevalim |
96a52cc
to
553b2b2
Compare
sorry, I accidentally closed PR once |
Sorry @QWYNG. I think there was some confusion. We should have two functions: |
@josevalim |
Thank you @QWYNG! 💟 |
@whatyouhide |
def frequencies_by(enumerable, key_fun) when is_function(key_fun) do | ||
reduce(enumerable, %{}, fn entry, acc -> | ||
key = key_fun.(entry) | ||
Map.update(acc, key, 1, &(&1 + 1)) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Given it's a library function and it should be as efficient as possible, could we manually expand the call to Map.update
to avoid the fun overhead? It's tiny, but things like that add up, especially in library functions.
Yeah, a PR would be welcome.
|
@michalmuskala @josevalim def frequencies(enumerable) do
reduce(enumerable, %{}, fn key, acc ->
case acc do
%{^key => value} ->
Map.put(acc, key, value + 1)
%{} ->
Map.put(acc, key, 1)
end
end)
end If it's alright with @michalmuskala, I will create PR. :) |
I would even do this: def frequencies(enumerable) do
reduce(enumerable, %{}, fn key, acc ->
case acc do
%{^key => value} -> %{acc | key => value + 1}
%{} -> Map.put(acc, key, 1)
end
end)
end A PR is welcome! |
Please go ahead @QWYNG. Thank you! |
Hi! Thank you for great programming language.
add frequencies and frequencies_by.
This is a discussion about this method.
https://groups.google.com/forum/?utm_medium=email&utm_source=footer#!msg/elixir-lang-core/hBRKIIy8QKE/2JlhpblqBgAJ
If any points to fix, don't hesitate to say.