简体   繁体   中英

Clojure core.logic generating parents

I have this code which does as I wish, it pulls the parents of the given person recursively:

(defn anc [child]
  (run* [q]
    (conde
     [(fresh [?p]
             (parento child ?p)
             (?== q [child ?p]))]
     [(fresh [?p ?gp]
             (parento child ?p)
             (parento ?p ?gp)
             (?== q [ ?p ?gp]))]
     [(fresh [?p ?gp ?ggp]
             (parento child ?p)
             (parento ?p ?gp)
             (parento ?gp ?ggp)
             (?== q [ ?gp ?ggp]))]
     )))

The problem is that for each generation I go back, I have to add a new test.

Is there a way to generalize this in core.logic?

I tried something and hopefully this can help you:

user=> (defrel parent c p)
user=> (fact parent :b :a)
nil
user=> (fact parent :c :b)
nil
user=> (fact parent :d :c)
nil

user=> (defn anso [c a] 
             (conde  
                 [(fresh [p x] 
                     (parent c p) 
                     (anso p x) 
                     (appendo [p] x a))] 
                 [(fresh [x] 
                     (parent c x) 
                     (== a [x]))])) 
#'user/anso

user=> (last (run* [q] (anso :c q)))
(:b :a)
user=> (last (run* [q] (anso :b q)))
[:a]
user=> (last (run* [q] (anso :d q)))
(:c :b :a)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM