# My solutions for problems No. 51-75 on 4clojure.com

### slution 69

Hi..sorry but I don't understand the solution 69...I've tried understand but its hard..would you explain it a bit more detailed..would be usefull for me..thanks a lot !!

### merge-with

Hi angel,

Thank you for stopping by. Let's read the code outside-in.

The outer reduce runs through all the (variable numbers of) input maps to accumulate results, and it takes two arguments: The first is an anonymous function defined in place (explained below), that does the result calculation for each input map; and the second argument is just the list of input maps (cons together the first and the rest).

The outer anonymous function of the outer reduce takes two arguments: ret is the accumulated result map so far, x is the next input map to be processed. This function uses a reduce function to run through the keys of x to accumulate results, starting with ret as the initial value.

At each step (i.e., at different key of x), an inner anonymous function is used to calculate the new result map. This function take two arguments: r is the existing result map, k is the key currently being worked on. The work is very simple: if the key k already exists in the result map r, we use the given function f to calculate the new value of k using the combination of its value in r (existing map) and its value in x (input map), and conj the new key-value pair (a two-element vector) to the result map; if k does not exist in r, we simply conj the key-value pair in x (accessed by the find function) to the result map.

Thinking on a higher level, we start with the first input map, taking it as the initial value of the result map, run through the rest of the input maps, and keep merging their values to the result map. Reduce is the perfect function for such a result accumulation purpose.

As you know, this is an implementation of merge-with function. My implementation, though a bit shorter, is actually similar to Clojure's own implementation, you can (source merge-with) in REPL to read theirs, which might be more readable, I am not sure.

I hope this explanation helps. Please feel free to ask more questions.

### thanks

Hi..thanks for the usefull answer..now it is clear for me...thanks again......

### You are welcome

Clojure is a fun language to play with. Happy coding

## Post new comment

• Allowed HTML tags: <a> <em> <strong> <cite> <blockquote> <code> <ul> <ol> <li> <dl> <dt> <dd> <div> <h1><h2><h3><sub><sup><b><i><u><font><img>
• You may post code using <code>...</code> (generic) or <?php ... ?> (highlighted PHP) tags.
• Lines and paragraphs break automatically.