title: Haskell: merging list of lists
body: <p>given a list of list pairs <code>::[a,a]</code>, I would like to return the possible combinations of lists, where the sublists have been merged on the last of one sublit matching head of the next.</p>
  
  <p>for example 
      -- combine two lists if they front and back match</p>
  
  <pre><code>merge :: Eq a =&gt; [[a]] -&gt; [[a]]
  merge (x:y:ys) | last x == head y = merge $ (x ++ (drop 1 y)) : ys
                 | otherwise    = []
  merge xs       = xs
  
  combinations :: Eq a =&gt; [[a]] -&gt; [[a]]
  combinations = nub . concatMap merge . permutations
  
  λ= merge [1,2] [2,3]
  [1,2,3]
  
  
  -- there should be no duplicate results
  λ= combinations [[1,3],[1,3],[1,3],[1,3],[2,1],[2,1],[2,1],[2,2],[3,2],[3,2],[3,2]]
  [[1,3,2,2,1,3,2,1,3,2,1,3],[1,3,2,1,3,2,2,1,3,2,1,3],1,3,2,1,3,2,1,3,2,2,1,3]]
  
  -- the result must be a completely merged list or an empty list
  λ= combinations [[1,3], [3,1], [2,2]]
  []
  
  λ= combinations [[1,3], [3, 1]]
  [[1,3,1],[3,1,3]]
  
  λ= combinations [[1,3],[3,1],[3,1]]
  [[3,1,3,1]]
  </code></pre>
  
  <p>I can't quite wrap my head around the recursion needed to do this efficiently.</p>