<font size="2"><span style="background-color:rgba(255,255,255,0)">It looks like fromListWith is indeed implemented with a left fold over insertWithKey, with the Map as the accumulator. However, in insertWithKey the value-combiner function has type 'k -> a -> k -> a' which means it can combine in either order (it doesn't have to do with the fold or iteration order at all). The docs say:</span></font><div><font size="2"><span style="-webkit-tap-highlight-color: rgba(26, 26, 26, 0.301961);"><br></span></font></div><div><pre><font face="Helvetica Neue, Helvetica, Arial, sans-serif" size="3"><span style="white-space:normal;background-color:rgba(255,255,255,0)"><span class="hs-comment">If the key does exist, the function will </span><span class="hs-comment">insert the pair @(key,f key new_value old_value)@.</span></span></font></pre></div><div><font size="2"><span style="-webkit-tap-highlight-color: rgba(26, 26, 26, 0.301961);"><br></span></font></div><div><font size="2"><span style="background-color:rgba(255,255,255,0)"></span><span style="-webkit-tap-highlight-color: rgba(26, 26, 26, 0.301961);">This doesn't really answer the "why" part of your question, but explains why you get [2, 1] instead of the reverse.<br></span></font><br>On Thursday, March 3, 2016, Niklas Hambüchen <<a href="mailto:mail@nh2.me">mail@nh2.me</a>> wrote:<br><blockquote class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex">Does anybody know why for fromListWith, the arguments to the combining<br>
function seem flipped?<br>
<br>
  > import Data.Map<br>
  > fromListWith (++) [('a',[1]),('a',[2])]<br>
<br>
  fromList [('a',[2,1])]<br>
<br>
I often use it to group things by some key, e.g.<br>
<br>
postsByUserId :: Map Int [Int]<br>
postsByUserId =<br>
fromListWith (++) [ (userId, [postId]) | (userId, postId) <- posts ]<br>
<br>
and regularly get tricked by the postIds being reversed in the result.<br>
<br>
This is especially unintuitive to me since:<br>
<br>
  > foldl (++) [] [[1],[2]]<br>
  [1,2]<br>
  > foldr (++) [] [[1],[2]]<br>
  [1,2]<br>
<br>
Any ideas?<br>
_______________________________________________<br>
Haskell-Cafe mailing list<br>
<a href="javascript:;" onclick="_e(event, 'cvml', 'Haskell-Cafe@haskell.org')">Haskell-Cafe@haskell.org</a><br>
<a href="http://mail.haskell.org/cgi-bin/mailman/listinfo/haskell-cafe" target="_blank">http://mail.haskell.org/cgi-bin/mailman/listinfo/haskell-cafe</a><br>
</blockquote></div>