Removing items from a map based on the contents of another map

Continue working through collective intelligence programming and use Clojure to write code. It works for me, but some parts are really ugly, so I thought that I would ask some experts here to help in order to clean it.

Suppose I have a map that looks like this (attached to recs "):

{"Superman Returns" 3.902419556891574, "Lady in the Water" 2.8325499182641614, "Snakes on a Plane" 3.7059737842895792, "The Night Listener" 3.3477895267131017, "You, Me and Dupree" 2.651006036204627, "Just My Luck" 2.5309807037655645} 

and I want to remove these elements with keys that are also on the map (tied to mymovies ):

 {"Snakes on a Plane" 4.5, "You, Me and Dupree" 1.0, "Superman Returns" 4.0} 

To get a card:

 {"Lady in the Water" 2.8325499182641614, "The Night Listener" 3.3477895267131017, "Just My Luck" 2.5309807037655645} 

The code I managed to do looks like this:

 (apply merge (map #(hash-map (first %) (second %)) (remove #(contains? mymovies (first %)) recs))) 

That seems pretty ugly to me. It doesn't seem to need to create a map from the value that I return from "remove". Is there a cleaner way to do this?

UPDATE: Joost's answer below triggered another idea. If I return the keys from two cards to the sets, I can use these keys:

 (select-keys recs (difference (set (keys recs)) (set (keys mymovies)))) 

Joost, thanks for turning me on to select the keys. I did not know about this feature before. Now let's move on to rewriting several other sections using this new found knowledge!

+6
source share
3 answers
 (apply dissoc recs (keys mymovies)) 
+13
source

In the following order, builds several keys for saving, and then extracts the β€œsubmenu” for these keys from the edges using the selection keys. He also exploits the fact that sets are predicates.

 (select-keys recs (remove (apply hash-set (keys mymovies)) (keys recs))) 
+2
source

I think the ponzao answer is best suited for this case, but I would not have thought to apply dissoc . Here are two solutions that I could come up with: I hope that viewing them will help with similar future problems.

Please note that the second solution will not be executed if your mymovies map contains nil or false.

 (into {} (for [[kv] recs :when (not (contains? mymovies k))] [kv])) (into {} (remove (comp mymovies key) recs)) 
0
source

Source: https://habr.com/ru/post/896666/


All Articles