title: Counting occurrences of a list item from a list?
body: <p>(See edit at the bottom of this post)</p>
  
  <p>I'm making a program in Elixir that counts the types of HTML tags from a list of tags that I've already obtained. This means that the key should be the tag and the value should be the count.</p>
  
  <p>e.g. in the following sample file</p>
  
  <pre><code>&lt;html&gt;&lt;head&gt;&lt;body&gt;&lt;sometag&gt;&lt;sometag&gt;&lt;sometag2&gt;&lt;sometag&gt;
  </code></pre>
  
  <p>My output should be something like the following:</p>
  
  <pre><code>html: 1
  head: 1
  body: 1
  sometag: 3
  sometag2: 1
  </code></pre>
  
  <p>Here is my code:</p>
  
  <pre><code>def tags(page) do
      taglist = Regex.scan(~r/&lt;[a-zA-Z0-9]+/, page)
  
      dict = Map.new()
  
      Enum.map(taglist, fn(x) -&gt; 
                          tag = String.to_atom(hd(x))
                          Map.put_new(dict, tag, 1)
                        end)
  
  end
  </code></pre>
  
  <p>I know I should be probably using <code>Enum.each</code> instead but when I do that my dictionary ends up just being empty instead of incorrect.</p>
  
  <p>With <code>Enum.map</code>, this is the output I receive:</p>
  
  <pre><code>iex(15)&gt; A3.test
  [%{"&lt;html" =&gt; 1}, %{"&lt;body" =&gt; 1}, %{"&lt;p" =&gt; 1}, %{"&lt;a" =&gt; 1}, %{"&lt;p" =&gt; 1},
   %{"&lt;a" =&gt; 1}, %{"&lt;p" =&gt; 1}, %{"&lt;a" =&gt; 1}, %{"&lt;p" =&gt; 1}, %{"&lt;a" =&gt; 1}]
  </code></pre>
  
  <p>As you can see, there are duplicate entries and it's turned into a list of dictionaries. For now I'm not even trying to get the count working, so long as the dictionary doesn't duplicate entries (which is why the value is always just "1").</p>
  
  <p>Thanks for any help.</p>
  
  <p>EDIT: ------------------</p>
  
  <p>Okay so I figured out that I need to use <code>Enum.reduce</code></p>
  
  <p>The following code produces the output I'm looking for (for now):</p>
  
  <pre><code>def tags(page) do
      rawTagList = Regex.scan(~r/&lt;[a-zA-Z0-9]+/, page)
      tagList = Enum.map(rawTagList, fn(tag) -&gt; String.to_atom(hd(tag)) end)
  
  
      Enum.reduce(tagList, %{}, fn(tag, acc) -&gt; 
                                      Map.put_new(acc, tag, 1)
                                  end)
  
  end
  </code></pre>
  
  <p>Output:</p>
  
  <pre><code>%{"&lt;a": 1, "&lt;body": 1, "&lt;html": 1, "&lt;p": 1}
  </code></pre>
  
  <p>Now I have to complete the challenge of actually counting the tags as I go...If anyone can offer any insight on that I'd be grateful!</p>