[Feature proposal] add counter / multiset function to Enum (or List) module

93 views
Skip to first unread message

David Whitlock

unread,
May 3, 2016, 3:00:57 AM5/3/16
to elixir-lang-core
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

José Valim

unread,
May 3, 2016, 3:17:47 AM5/3/16
to elixir-l...@googlegroups.com
Here is a simpler version with Map.update:

    Enum.reduce items, %{}, fn item, map ->
      Map.update(map, item, 1, & &1 + 1)
    end

To be quite honest, I don't think this particular case is important enough to warrant its own function. :)

Thank you David!



José Valim
Skype: jv.ptec
Founder and Director of R&D

--
You received this message because you are subscribed to the Google Groups "elixir-lang-core" group.
To unsubscribe from this group and stop receiving emails from it, send an email to elixir-lang-co...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/elixir-lang-core/03ad0fd8-b53f-4250-b345-0b9105845345%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

David Whitlock

unread,
May 3, 2016, 3:33:54 AM5/3/16
to elixir-lang-core
Ok. Well, at least your solution can provide documentation for this :)
Reply all
Reply to author
Forward
0 new messages