Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>From what I understand, you want to take a list of type <code>[[(Int, Int)]]</code> and sum the first element of any tuple that has the same second element. You can completely disregard that it is a list of lists and just <code>concat</code> right away, unless the structure of the lists can help you determine which elements should be added (but I have not seem any evidence that would indicate that). Then you get the minimum <code>snd</code>, sort the list by the <code>snd</code> values, and recurse through the list, calling <code>span :: (a -&gt; Bool) -&gt; [a] -&gt; ([a], [a])</code> which takes a predicate and splits a list at the last element which satisfies the predicate. Since the list is sorted, this will capture all of the tuples with same <code>snd</code>. Then we fold over that list of tuples.</p> <pre><code>add :: [[(Int, Int)]] -&gt; [(Int, Int)] add list = addT (minBound :: Int) $ sortBy sortF (concat list) where sortF (_,x) (_,y) | x &lt; y = LT | x &gt; y = GT | x == y = EQ addT n list = sumFunc $ span (sndIs n) list where sndIs n (_,y) = y == n sumFunc ([],b)= addT (n+1) b sumFunc (a,[])= [(foldr (\(x,y) (w,v) -&gt; (x+w,y)) (0,0) a)] sumFunc (a,b) = (foldr (\(x,y) (w,v) -&gt; (x+w,y)) (0,0) a):(addT (n+1) b) </code></pre> <p>then :</p> <pre><code>&gt; add [[(1,2), (3,0)], [(3,1), (7,0)]] &gt; [(10,0),(3,1),(1,2)] </code></pre> <p>The only problem is the complexity is very bad (try <code>add [[(43, minBound :: Int), (10, maxBound :: Int)]]</code>). If you want to make it faster, you should get all the <code>snd</code>s first and only call addT with those, if you are likely to be using this function on values that differ greatly.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
 

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