clojure找到任意嵌套的密钥

时间:2016-02-25 15:29:00

标签: clojure specter

Clojure中是否有一种简单的方法(可能使用specter)来过滤集合,具体取决于具有已知名称的任意嵌套键是否包含元素?

实施例。 :

(def coll [{:res [{:a [{:thekey [
                          "the value I am looking for"
                      ...
                     ]
            }
           ]}
      {:res ...}
      {:res ...}
      ]}])

知道:a可以有不同的名称,并且:thekey可以嵌套在其他地方。 让我们说我想做:

 #(find-nested :thekey #{"the value I am looking for"} coll) ;; returns a vector containing the first element in coll (and maybe others)

1 个答案:

答案 0 :(得分:3)

使用拉链。 在repl:

user> coll
[{:res [{:a [{:thekey ["the value I am looking for"]}]} {:res 1} {:res 1}]}]

user> (require '[clojure.zip :as z])
nil

user> (def cc (z/zipper coll? seq nil coll))
#'user/cc

user> (loop [x cc]
        (if (= (z/node x) :thekey)
          (z/node (z/next x))
          (recur (z/next x))))
["the value I am looking for"]

<强>更新

这个版本存在缺陷,因为它并不关心:key是地图中的关键,或者只是向量中的关键字,因此它会为coll [[:thekey [1 2 3]]]提供不必要的结果。这是一个更新版本:

(defn lookup-key [k coll]
  (let [coll-zip (z/zipper coll? #(if (map? %) (vals %) %) nil coll)]
    (loop [x coll-zip]
      (when-not (z/end? x)
        (if-let [v (-> x z/node k)] v (recur (z/next x)))))))

在repl中:

user> (lookup-key :thekey coll)
["the value I am looking for"]

user> (lookup-key :absent coll)
nil

假设我们在coll中的向量中有相同的关键字:

(def coll [{:res [:thekey
                  {:a [{:thekey ["the value I am looking for"]}]}
                  {:res 1} {:res 1}]}])
#'user/coll

user> (lookup-key :thekey coll)
["the value I am looking for"]

这就是我们所需要的。

相关问题