iGEL
iGEL

Reputation: 17392

Test whether a list doesn't contain a value

I have a vector with maps (each with an id) and I want to select only the maps which id is not in a list of ids. What's the most idiomatic way to do that?

(def input [{:id 1 :asd 8} {:id 2 :asd 4} {:id 3 :asd 7} {:id 4 :asd 4}])
(def connected-ids '(1 3))

;; this is what I want to get:
(def not-connected [{:id 2 :asd 8} {:id 4 :asd 4})

The returned collection doesn't have to be a vector.

Upvotes: 2

Views: 150

Answers (1)

Magos
Magos

Reputation: 3014

My suggestion would be to

  1. Keep the connected IDs in a set: (def connected-ids #{1 3})
    This step gives us both deduplication (it doesn't make sense to have an ID in the blacklist twice) and a handy membership test function - simply call the set as a function and it will return the (one) argument iff it is a member, else nil. It's also cheaper in terms of asymptotic time than scanning a list to check whether a value is in it.
  2. Use remove to remove items that we don't want:

 

(def not-connected (remove (comp connected-ids :id) input))

Upvotes: 4

Related Questions