Craftsman at work

I'm Artur Karbone, coding software architect and independent IT consultant and this is my blog about craftsmanship, architecture, distributed systems, management and much more.

Elixir Exercise #2 from "Seven more languages ... "

  • The problem

Given a list of atoms, build a function called wordcount that returns a keyword list, where the keys are atoms from the list and the values are the number of occurrences of that word in the list. For example, wordcount([: one, :two, :two]) returns [one: 1, two: 2].

  • The solution

Let's leverage pipelines here:

defmodule MyEnum do  
    def word_count(words)  do
        words |> 
        Enum.group_by(&(&1)) |> 
        Enum.map(fn({key,value})->{key,Enum.count(value)} end)
    end
end  
comments powered by Disqus