I'm using Datascript to query a tree structure for the last common ancestor of 2 nodes having given names, here's what I've got so far, but it's really slow -- any idea why (or is there a better way)?
(defn lca
"Last common ancestor"
[db name1 name2]
(d/q '[
:find [(pull ?anc [:db/id :name]) ...]
:in $ % ?name1 ?name2
:where
(?node1 :name ?name1)
(?node2 :name ?name2)
(anc ?anc1 ?node1)
(anc ?anc2 ?node2)
[(not= ?anc1 ?anc2)]
(parent ?anc ?anc1)
(parent ?anc ?anc2)
]
@db
'[
[ (parent ?par ?child)
(?par :children ?child)]
[ (anc ?par ?child)
(?par :children ?child)]
[ (anc ?anc ?child)
(?par :children ?child)
(anc ?anc ?par)]
]
name1
name2))
I initially was going to use not
to exclude all higher ancestors than the
last common one, but Datascript currently doesn't support not
hence the two
parent clauses.
The schema is:
:children {:db/valueType :db.type/ref
:db/cardinality :db.cardinality/many
:db/index true}
:name {:db/index true}