【问题标题】:Tree search in Clojure core.logicClojure core.logic 中的树搜索
【发布时间】:2016-09-03 23:24:40
【问题描述】:

一段时间以来,我一直对模型化问题感到困惑,我不得不承认我不知道如何在core.logic 中“正确”解决它。

很容易说明:给定一棵树(非循环单向图)和其中的一个顶点,您如何使用core.logic 定义一个目标,该目标允许 lvar 成为给定顶点的任何可到达顶点?

我已经开始做一些尽可能简单的事情:

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

鉴于这种配置,我的目标是定义一个目标,它允许 lvar 采用 ['a 'b 'c 'd] 中的值。使用“1 hop”获得可到达的顶点很简单:

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

您可以为 2 跳添加变量等等,但是...可以概括吗?我想用类似的东西定义一个 lvar 列表

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

但经过几次尝试,我必须承认我不确定这是正确的方法。

【问题讨论】:

    标签: clojure tree clojure-core.logic tree-search


    【解决方案1】:
    (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]))
    

    递归目标:

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

    测试

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

    【讨论】:

      【解决方案2】:

      感谢您的帮助!

      其实我明白了

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

      我问这个问题是因为我很久没有练习逻辑编程但现在我觉得它又来了^^

      无论如何,非常感谢您的回答,这给了我一个额外的观点。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-08-23
        • 1970-01-01
        • 2020-05-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多