我正在尝试在 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]))
()
最佳答案
您不需要第二个模式,即 [_ [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)))
https://stackoverflow.com/questions/16370327/