Skip to content

Instantly share code, notes, and snippets.

@orb
Created February 8, 2015 22:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save orb/880230bb3e87f5618682 to your computer and use it in GitHub Desktop.
Save orb/880230bb3e87f5618682 to your computer and use it in GitHub Desktop.
clojure unification tests
(ns hufflepuff.uni
(:require [clojure.core.logic :refer [defnc fnc]]
[clojure.core.logic.unifier :refer [unifier unify]]))
(defnc numberc [x]
(number? x))
(defnc symbolc [x]
(symbol? x))
(defnc not-numberc [x]
(not (number? x)))
(defn u+ [& pairs]
(loop [u {} pairs pairs]
(if (seq pairs)
(when-let [u' (unifier {:as u} (first pairs))]
(recur (merge u u')
(rest pairs)))
u)))
(defn q [data query]
(filter #(u+ (conj query %)) data))
(def things [{:name "thing 1" :color :red}
{:name "thing 2" :color :blue}
{:name "thing 3" :color :red}])
(comment
(unifier '[dog
dog])
;; {}
(unifier '[dog
cat])
;; nil
(unifier '[?animal
dog])
;; {?animal dog}
(unifier '[?foo
?bar])
;; {?foo ?bar}
(unifier '[{:name bob :age 42}
{:name ?X :age ?Y}])
;; {?X bob, ?Y 42}
(unifier '[{:name bob :age 42}
{:name ?X}])
;; nil
(unifier '[{:a [?b (?c [?d {:e ?e}])]}
{:a [:b (:c [:d {:e :e}])]}])
;; {?e :e, ?d :d, ?c :c, ?b :b}
(unifier '[(foo (bar ?X) baz)
(foo ?Y ?X)])
;;{?Y (bar baz), ?X baz}
(unifier '[[?num ?animal] [:magical :unicorn]])
;; {?animal :unicorn, ?num :magical}
(unifier {:when {'?num numberc}}
'[[?num ?animal]
[:magical :unicorn]])
;; nil
(unifier {:when {'?num numberc}}
'[[?num ?animal]
[42 :unicorn]])
;; {?animal :unicorn, ?num 42}
(unifier {:as '{?a 3}}
'[?a ?b])
;; {?b 3, ?a 3}
(unifier {:as '{?a 3 ?b 4}}
'[?a ?b])
;; nil
(unifier {:as '{?a ?b}}
'[(?a 4) (?a ?b)])
;; {?b 4, ?a 4}
(unifier {:as (unifier '[?a ?b])}
'[?c (?a ?b)])
;; {?a ?b, ?c (?b ?b)}
(unifier {:as (unifier '[?a ?b])}¯
'[(?c 5) (?a ?b)])
;; {?b 5, ?a 5, ?c 5}
(q things '[{:name ?name :color :red}])
;; ({:color :red, :name "thing 1"} {:color :red, :name "thing 3"})
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment