On Thu, Jan 20, 2011 at 3:34 AM, Stefan Rohlfing
<stefan.rohlf...@gmail.com> wrote:
> Hi John,
> Thank you very much for your correction of my code! my-merge-with is working
> perfectly now.
> There is just one thing: I always want to understand my errors so that I can
> learn from them. However, I still don't understand why my implementation did
> not work. Looking at my code I am thinking everything should be fine as all
> key/val pairs are added to the map acc of the outer reduce (or so is my
> assumption).

That's exactly it though: it doesn't add the key to acc.  It creates a
new copy of acc with the updated key and returns that result (it
doesn't update acc in place).  For each iteration of the inner reduce,
it was starting off with the original acc, trying to add the key, and
then the updated map would get discarded... except for the last entry
for each of the maps.

For the first run, acc is an empty map, and then the inner reduce
would try to add the keys.  So it was basically doing
  (assoc {} :a 1) => {:a 1}
  (assoc {} :b 2) => {:b 2}

The last result is kept as the result of the inner reduce operation,
which then becomes the next intermediate result for the outer reduce
operation.  Then, we run through the second map:
  (assoc {:b 2} :a 9) => {:b 2 :a 9}
  (assoc {:b 2} :b 100) => {:b 100}
  (assoc {:b 2} :c 0) => {:b 2 :c 0}

Once again, the last result is kept as the result of the reduce
operation.  This also happens to be the last result of the outer
reduce as well, and ends up being your answer.  Hopefully, you can see
how the intermediate results were being discarded now.  It sometimes
difficult to remember that you're operating on immutable data. :-)

-John

-- 
You received this message because you are subscribed to the Google
Groups "Clojure" group.
To post to this group, send email to clojure@googlegroups.com
Note that posts from new members are moderated - please be patient with your 
first post.
To unsubscribe from this group, send email to
clojure+unsubscr...@googlegroups.com
For more options, visit this group at
http://groups.google.com/group/clojure?hl=en

Reply via email to