Hi all,
In many languages, there is a multiset functionality (in Python, this is called Counter), which produces a map with the counts of each item from a list. For example, you might want to do a word search of a text stream, and after converting the text to a list of words, you can then call the multiset / counter function and it would produce something like this:
%{"the" => 34, "cat" => 2, "mat" => 7}
I've found this functionality very useful in the past, and I was wondering if it might be added to the standard library.
My proposal is to add something like the following function to the Enum module:
def counter(items) do
Enum.reduce items, %{}, fn key, map ->
current = case :maps.find(key, map) do
{:ok, value} -> value
:error -> 0
end
:maps.put(key, current + 1, map)
end
end
This would take any list and return a map containing the 'counts' of each item. I don't see the need for creating a separate multiset type. It can just be used like any other map.
Please let me know what you think,
David