1

我有这个代码,它可以按照我的意愿执行,它递归地拉出给定人的父母:

(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]))]
     )))

问题是,对于我回去的每一代,我都必须添加一个新的测试。

有没有办法在 core.logic 中概括这一点?

4

1 回答 1

1

我尝试了一些东西,希望这可以帮助你:

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)
于 2013-01-08T12:32:58.080 回答