Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>This is a "keyed" operation, and can be solved quite easily with a little help from the standard library. </p> <pre><code>import qualified Data.Map as M </code></pre> <p><code>Data.Map</code> implements finite associative maps -- i.e. <code>M.Map k a</code> has a set of keys of type <code>k</code>, and to each key it associates a value of type <code>a</code>.</p> <p>The extremely useful function for this kind of problem is <a href="http://www.haskell.org/ghc/docs/6.12.1/html/libraries/containers-0.3.0.0/Data-Map.html#v%3AfromListWith"><code>fromListWith</code></a>:</p> <pre><code>M.fromListWith :: (a -&gt; a -&gt; a) -&gt; [(k,a)] -&gt; M.Map k a </code></pre> <p>The second argument, the list of <code>(k,a)</code> tuples, are simply associations, assocating a given key to a given value. The first argument is a combining function, which says what to do to the values if duplicate keys appear in the list. </p> <p>You must also use <code>M.toList :: M.Map k a -&gt; [(k,a)]</code> which gives you back the list of associations stored in the Map. Here's an example:</p> <pre><code>ghci&gt; M.toList (M.fromListWith (+) [(1,2), (2,3), (1,4), (3,5)]) [(1,6),(2,3),(3,5)] </code></pre> <p>Note how the keys are the <em>first</em> elements of the tuples, the opposite of how you have stated your problem. We have combined <code>(1,2)</code> and <code>(1,4)</code> into <code>(1,6)</code>. We added because we gave the combining function <code>(+)</code>.</p> <p>This one function solves the brunt of your problem -- the rest is just a little plumbing, which I will leave to you.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload