Skip to content

Instantly share code, notes, and snippets.

@uris77
Last active October 6, 2015 01:59
Show Gist options
  • Save uris77/298304673d04bdc904a0 to your computer and use it in GitHub Desktop.
Save uris77/298304673d04bdc904a0 to your computer and use it in GitHub Desktop.
Clojure trick

Naive way to filter a list of maps in clojure:

(defn matches-addresses? [addresses]
  (fn [it]
    (lazy-seq  (loop [as addresses
                      acc [(quote or)]]
                 (if (seq (first as))
                   (recur (rest as) (conj acc (lazy-seq [(quote =) (first as) (get it :private-ip-address)])))
                   acc)))))
                   
(defn find-matching-addresses
  [should-match addresses]
  (filter (fn [it]
            (eval (apply (matches-addresses? should-match) [it])))
          addresses))

Better way:

(defn match-addresses? 
  [addresses]
  (let [as (set addresses)]
    (fn [it]
      (as (:private-ip-address it)))))
      
(defn find-matching-addresses
  [should-match addresses]
  (filter (match-addresses? should-match)
          addresses))

      
(filter (matches-addresses? ["10.2.1.122" "10.2.1.155"]) [{:private-ip-address "10.2.0.0"} {:private-ip-address "10.2.1.122"} {:private-ip-address "10.2.1.155"}])
 => ({:private-ip-address "10.2.0.0"} {:private-ip-address "10.2.1.122"} {:private-ip-address "10.2.1.155"})
 
(find-matching-addresses ["10.2.1.1" "10.2.1.155"] 
                        [{:private-ip-address "10.2.0.0"} 
                         {:private-ip-address "10.2.1.122"} 
                         {:private-ip-address "10.2.1.155"}])
=> ({:private-ip-address "10.2.1.155"})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment