-w4plq
Last Updated: February 25, 2016
·
1.236K
· samn
B0b58c82a095beb534ac72526541dcc6

Find Elements in a Collection Using core.logic

Here's a handy macro for using core.logic to find an element in a collection that matches a set of rules.

(defmacro membero-such
  "Convenience macro for finding elements in a 
  collection that match a set of rules.
  Generates a new fresh lvar named ~lvar,
  which should be membero coll.  Pass additional
  rules in body.  Unify lvar with something else
  so its value can escape the scope of this macro."
  [lvar coll & body]
  `(clojure.core.logic/fresh [~lvar]
     (clojure.core.logic/membero ~lvar ~coll)
     ~@body))

You'll want to unify lvar (which is made fresh) with something else so its value can escape the scope of the macro body.

Example usage:

(defn find-el
  [el coll out]
  (membero-such e coll
    (clojure.core.logic/== e el)
    (clojure.core.logic/== e out)))

(clojure.core.logic/run* [q]
  (find-el :b [:a :b :c] q)) ; => (:b)
Say Thanks
Respond