2

I have two hash maps and am trying to merge them together while only keeping the keys found in both maps.
Ex:

{a true, b true, c true, d true, e true}
merged with {c true, d true, e true, f true}
would yield {c true, d true, e true}

I am pretty new to Clojure and just can't seem to figure out how to do this. Thanks

3
  • How are you merging the values? You can use select-keys to select the keys you need from the second map. Commented Feb 8, 2018 at 18:00
  • Thats what I need help with. I want to merge them as I showed in the code but I can't figure out how to do so Commented Feb 8, 2018 at 18:01
  • 1
    So you just want to discard the first map? Or do you want to combine the corresponding values in some way? It's not clear how a => true in the first map and a => true in the second combine to result in a => true in the result. Commented Feb 8, 2018 at 18:42

2 Answers 2

7

There is a select-keys function in the standard library

(let [a {:a true :b true :c true :d true :e true}
      b {:c true :d true :e true :f true}
      b-keys (keys b)]
  (select-keys a b-keys))
#=> {:c true, :d true, :e true}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks that was exactly what I was looking for
1

Apart from select-keys, min-key is also useful. This function can be used with an arbitrary number of map

(defn min-merge [& ms]
  (let [min-keys (keys (apply min-key count ms))]
    (select-keys (apply merge ms) min-keys)))

Try

user=> (min-merge {:a 1 :b 2} {:a 3} {:a 4 :b 5 :c 6})
{:a 4}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.