【问题标题】:Why does my clojure.core.logic nonmember function return two values?为什么我的 clojure.core.logic 非成员函数返回两个值?
【发布时间】:2013-05-04 03:37:30
【问题描述】:

我正在尝试在clojure.core.logic 中实现与membero 相反的功能,但它返回的是两个值而不是一个。否则,它可以正常工作(当值在列表中时不返回任何内容,当不在列表中时返回)。

(defne nonmembero
  "A relation where l is a collection, such that l does not contain x"
  [x l]
  ([_ ()])
  ([_ [head]]
     (!= x head))
  ([_ [head . tail]]
     (!= x head)
     (nonmembero x tail)))

示例运行:

user> (run* [x] (nonmembero 1 [2 3 4 5]))
(_0 _0)
user> (run* [x] (nonmembero 1 [2 3 1 4 5]))
()

【问题讨论】:

    标签: clojure clojure-core.logic


    【解决方案1】:

    您不需要第二个模式,即[_ [head]。这导致 core.logic 引擎的搜索空间出现新分支,因此导致 2 输出。最后一个模式,即[head . tail] 足以处理列表中只有一个元素的情况。现在您的解决方案变为:

    (defne nonmembero
      "A relation where l is a collection, such that l does not contain x"
      [x l]
      ([_ ()])
      ([_ [head . tail]]
         (!= x head)
         (nonmembero x tail)))
    

    【讨论】:

      【解决方案2】:

      上面的代码有问题。它找到了以下解决方案

      (run* [q](== q 1)(nonmembero q [1 2 3]))  =>  (1)
      

      下面给出了预期的结果

      (run* [q](== q 1)(nonmembero2 q [1 2 3]))  => ()
      

      nonmembero2 在哪里

      (defn nonmembero2
        [x l]
        (fresh [h t]
          (conde
            [(== l ())]
            [(conso h t l)
             (!= x h)
             (nonmembero2 x t)])))
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-04-18
        • 2015-11-15
        • 1970-01-01
        • 2021-12-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-06-29
        相关资源
        最近更新 更多