简体   繁体   English

在Clojure core.logic中搜索树

[英]Tree search in Clojure core.logic

I've been puzzled by a modelisation problem for some time and I have to confess I have no idea how I could "properly" solve it in core.logic . 一段时间以来我一直对模型化问题感到困惑,我不得不承认我不知道如何在core.logic “正确”解决它。

It is very easy to state: given a tree (acyclic unidirectional oriented graph) and a vertex in it, how do you use core.logic to define a goal which allow a lvar to be any reachable vertex from the given vertex? 很容易说明:给定一个树(非循环单向导向图)和其中的顶点,如何使用core.logic定义一个目标,允许lvar成为来自给定顶点的任何可到达顶点?

I've started out with something as simple as possible: 我开始时尽可能简单:

(defrel vertex x)
(defrel child)
(def facts
  (pldb/db
    [vertex 'a]
    [vertex 'b] [child 'a 'b]
    [vertex 'c] [child 'b 'c]
    [vertex 'd] [child 'c 'd]))

Given this configuration, I aim at defining a goal which allows a lvar to take values in ['a 'b 'c 'd]. 鉴于这种配置,我的目标是定义一个允许lvar在['a'b'c'd]中取值的目标。 It's straightforward to get reachable vertices with "1 hop": 使用“1 hop”获得可到达的顶点非常简单:

(defn reachableo
  [a]
  (fresh [q]
    (child a q)))

and you can add variables for 2 hops and so on but... can it be generalized? 并且你可以添加2跳等变量,但是......可以推广吗? I've thought to define a list of lvar with something like 我曾经想过用类似的东西定义一个lvar列表

(let [vars (repeatedly lvar)]
  (map #(child (nth vars %) (nth vars (inc %)))
       (-> vars count dec range))
  (all
    ...))

but several attempts later, I must confess I'm not sure it's the correct way to go. 但是后来几次尝试,我必须承认我不确定这是正确的方法。

(pldb/db-rel vertex x)
(pldb/db-rel child parent child)
(def facts
  (pldb/db
    [vertex 'a]
    [vertex 'b] [child 'a 'b]
    [vertex 'c] [child 'b 'c]
    [vertex 'd] [child 'c 'd]))

The recursive goal: 递归目标:

(defn reachable° [from to]
  (l/fresh [v]
    (l/conde
      [(child from to)]
      [(child from v) (reachable° v to)])))

Testing 测试

=> (pldb/with-db facts
     (vec (l/run* [to] (reachable° 'a to))))
[b c d]

thanks for your help! 谢谢你的帮助!

Actually I got 其实我得到了

(defn order-relationo
  "Abstract the general pattern of a order relation in a logic, relational way."
  [relation x y]
  (conde
   [(relation x y)]
   [(fresh [z]
      (relation x z)
      (order-relationo relation z y))]))

(def kino
  "A goal where the two inputs x and y share kinship: x is an ancestor of y and
  y a descandant of x."
  (partial order-relationo child))

I asked this question because it was a long time I hadn't practiced logic programming but now I feel it's coming again ^^ 我问了这个问题,因为很长一段时间我没有练过逻辑编程,但现在我觉得它又来了^^

Anyway, thanks a lot for your answer which gives me an additional viewpoint. 无论如何,非常感谢你的回答,这给了我一个额外的观点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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