从Clojure core.logic中提取地图元素

时间:2013-01-04 16:20:45

标签: clojure clojure-core.logic

我正在尝试使用Clojure core.logic从地图中提取数据。这段代码就像我想要的那样:

 (run 10 [q] 
   (fresh [?id ?type ?name] 
      (membero ?type [:t2 :t1])
      (== q [?id ?name])
      (membero {:id ?id :type ?type :name ?name}  
           [
           {:id 1 :type :t1 :name "one"}
           {:id 2 :type :t2 :name "two"}
           ])))
=> ([2 "two"] [1 "one"])

但是,如果我向地图添加一些其他元素,则无法匹配:

(run 10 [q] 
   (fresh [?id ?type ?name] 
      (membero ?type [:t2 :t1])
      (== q [?id ?name])
      (membero {:id ?id :type ?type :name ?name}  
           [
           {:id 1 :type :t1 :name "one" :other1 :o1}
           {:id 2 :type :t2 :name "two" :other2 :o2}
           ])))

我理解为什么matcho不起作用,因为地图不再相同。我的问题是,我怎样才能改变它以便它再次起作用?如何让它仅匹配地图中的某些键,或者如何使其匹配地图可能具有的任何随机键?

编辑:

我使用patial-map(感谢https://github.com/clojure/core.logic/pull/10

让它工作
(run 10 [q] 
   (fresh [?id ?type ?name] 
          (membero ?type [:t2 :t1])
          (== q [?id ?name])
          (membero (partial-map {:id ?id :type ?type :name ?name} )
                   [
                    {:id 1 :type :t1 :name "one" :other1 :o2}
                    {:id 2 :type :t2 :name "two" :other2 :o1}
                    ])))

但是我发现应该使用featurec代替partial-map。我的新问题:如何更改此问题以使用featurec

1 个答案:

答案 0 :(得分:6)

回答我自己的问题:

以下是工作代码:

(run 10 [q] 
   (fresh [?id ?type ?name ?pm] 
          (membero ?type [:t2 :t1])
          (== q [?id ?name])
          (featurec ?pm  {:id ?id :type ?type :name ?name} )
          (membero ?pm
                   [
                    {:id 1 :type :t1 :name "one" :other1 :o2}
                    {:id 2 :type :t2 :name "two" :other2 :o1 :another :ao2}
                    {:id 3 :type :t3 :name "three" :other2 :o1 :another :ao1}
                    ]))))

此代码允许我从地图中提取值,但只关注真正重要的键。其余的键值对将被忽略。