[英]clojure core.logic counting elements in a set
我尝试在core.logic中做这样的事情
(defn count-different-elements-in-list [coll]
(count (set coll)))
这适用于整数就好了
(should= 1 (count-different-elements-in-list '(1 1 1)))
(should= 2 (count-different-elements-in-list '(1 1 2)))
(should= 3 (count-different-elements-in-list '(1 3 2)))
但现在我正在尝试使用core.logic来解决一些问题而且它会变得混乱
(run* [a b c]
;;the variables get values between 1 and 3
(fd/in a b c (fd/interval 1 3))
;; in the list there should only be 2 different values
(== 2 (count-different-elements-in-list '(a b c))))
但问题来了,abc不会作为值传递给函数。 它们作为变量传递。 有三个变量count-different-elements-in-list返回总是3,core.logic找不到解决方案(空列表)。
但我正在寻找这个结果。
([1 1 2] [1 2 1] [2 1 1]
[1 1 3] [1 3 1] [3 1 1]
[2 2 1] [2 1 2] [1 2 2]
[2 2 3] [2 3 2] [3 2 2]
[3 3 1] [3 1 3] [1 3 3]
[3 3 2] [3 2 3] [2 3 3])
您需要将core.logic/project
逻辑变量转换为非关系目标,例如正常函数count-different-elements-in-list
。 遗憾的是,您无法project
有限域逻辑变量,如a
, b
和c
,它们不受单个值的约束。 (见: 这个问题 )
在您拥有的示例中,您可以为生成的范围和membero
换出fd/in
和fd/interval
。 这将删除无约束的有限域变量,保持整数的范围约束,并允许投影。
(def interval (vec (range 1 4)))
(run* [a b c]
(membero a interval)
(membero b interval)
(membero c interval)
(project [a b c]
(== 2 (count-different-elements-in-list (list a b c)))))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.