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*
www.plataformatec.com.br
Skype: jv.ptec
Founder and Director of R&D

On Tue, May 3, 2016 at 9:00 AM, David Whitlock <[email protected]>
wrote:

> 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
>
> --
> 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 [email protected].
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/elixir-lang-core/03ad0fd8-b53f-4250-b345-0b9105845345%40googlegroups.com
> <https://groups.google.com/d/msgid/elixir-lang-core/03ad0fd8-b53f-4250-b345-0b9105845345%40googlegroups.com?utm_medium=email&utm_source=footer>
> .
> For more options, visit https://groups.google.com/d/optout.
>

-- 
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 [email protected].
To view this discussion on the web visit 
https://groups.google.com/d/msgid/elixir-lang-core/CAGnRm4KVh2sUgHJ0nW8wqMN31cFZMWUWS7mP-zqZnJdd0ajSxA%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to