Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@terjesb
Forked from jonase/gist:3115120
Last active August 29, 2015 14:21
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 terjesb/fbb6cd1026d64c834fdd to your computer and use it in GitHub Desktop.
Save terjesb/fbb6cd1026d64c834fdd to your computer and use it in GitHub Desktop.
(use '[datomic.api :only [db q] :as d])
(def schema
[{:db/doc "A persons name"
:db/id #db/id[:db.part/db]
:db/ident :name
:db/valueType :db.type/string
:db/cardinality :db.cardinality/one
:db.install/_attribute :db.part/db}
{:db/doc "A persons children"
:db/id #db/id[:db.part/db]
:db/ident :child
:db/valueType :db.type/ref
:db/cardinality :db.cardinality/many
:db.install/_attribute :db.part/db}])
(def tx-data
(let [[victor kathleen joseph
wendy jeffrey rosa
harry grace william]
(repeatedly #(d/tempid :db.part/user))]
[[:db/add victor :name "Victor"]
[:db/add kathleen :name "Kathleen"]
[:db/add joseph :name "Joseph"]
[:db/add wendy :name "Wendy"]
[:db/add jeffrey :name "Jeffrey"]
[:db/add rosa :name "Rosa"]
[:db/add harry :name "Harry"]
[:db/add grace :name "Grace"]
[:db/add william :name "William"]
[:db/add victor :child joseph]
[:db/add kathleen :child joseph]
[:db/add joseph :child harry]
[:db/add wendy :child harry]
[:db/add jeffrey :child grace]
[:db/add rosa :child grace]
[:db/add harry :child william]
[:db/add grace :child william]]))
(def genealogy
(let [uri "datomic:mem://genealogy"]
(d/delete-database uri)
(d/create-database uri)
(let [conn (d/connect uri)]
(d/transact conn schema)
(d/transact conn tx-data)
(db conn))))
(def parent
;; ?a is a parent of ?b
'[[[parent ?a ?b]
[?a-id :name ?a]
[?b-id :name ?b]
[?a-id :child ?b-id]]])
(def ancestor
; ?a is an anscestor of ?b
'[[[ancestor ?a ?b]
[parent ?a ?b]]
[[ancestor ?a ?b]
[parent ?a ?x]
[ancestor ?x ?b]]])
(def rules (concat parent ancestor))
;; Who are Wendys children?
;; (works as expected)
(q '[:find ?c
:in $ %
:where
[parent "Wendy" ?c]]
genealogy rules)
;; #<HashSet [["Harry"]]>
;; Who are Harry's parents?
;; (works as expected)
(q '[:find ?p
:in $ %
:where
[parent ?p "Harry"]]
genealogy rules)
;; => #<HashSet [["Joseph"], ["Wendy"]]>
;; Who are Harrys ancestors?
(q '[:find ?a
:in $ %
:where
[ancestor ?a "Harry"]]
genealogy rules)
;; => #<HashSet [["Joseph"], ["Wendy"]]> (0.8.3343)
;; => #<HashSet [["Joseph"], ["Wendy"] ["Victor"] ["Kathleen"]]> (0.8.3372)
;; Who are Jeffreys descendants?
(q '[:find ?d
:in $ %
:where
[ancestor "Jeffrey" ?d]]
genealogy rules)
;; => #<HashSet [["Grace"]]>
;; Should return #<HashSet [["Grace"] ["William"]]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment