4

我已将我的数据建模为嵌入式向量。我需要找出这些向量中是否存在一个元素。我有下面的代码可以正确执行。但是,我想就更惯用的方式提出建议。

(defn exists-in-vector?
  [my-vec my-sym]
  (= my-sym (first my-vec)))

(defn exists-in-vectors?
  [all-vectors my-symbol]
  (empty? (for [first-vector all-vectors
               second-vector first-vector
               third-vector second-vector
               :when (exists-in-vector? third-vector my-symbol)
               :while (exists-in-vector? third-vector my-symbol)]
           true)))

> (exists-in-vectors? [[[[:a 20] [:b :30]] [[:c 20] [:d :30]]]
                      [[[:h 20] [:g :30]] [[:f 20] [:e :30]]]]
                      :a) => true
4

3 回答 3

9

这是“扁平化”正是您想要的少数情况之一:

(def vectors [[[[:a 20] [:b :30]] [[:c 20] [:d :30]]] 
             [[[:h 20] [:g :30]] [[:f 20] [:e :30]]]])

(some #{:g} (flatten vectors))
;=> :g

(some #{:k} (flatten vectors))
;=> nil

顺便说一句,flatten 的定义很有趣。(源扁平化)或http://clojuredocs.org/clojure_core/clojure.core/flatten

(定义扁平化
  “采用顺序事物的任何嵌套组合(列表、向量、
  等)并将它们的内容作为一个单一的、扁平的序列返回。
  (flatten nil) 返回 nil。”
  {:添加“1.2”
   :静态真}
  [X]
  (过滤器(补充顺序?)
          (休息(tree-seq 顺序?seq x))))
于 2013-04-28T04:46:18.353 回答
5

嵌套向量可以被认为是一棵树

(def tree [[[[:a 20] [:b :30]] [[:c 20] [:d :30]]] 
           [[[:h 20] [:g :30]] [[:f 20] [:e :30]]]])

(some #(= :a %) (tree-seq vector? identity tree))
;=> true

(some #(= :k %) (tree-seq vector? identity tree))
;=> nil
于 2013-04-27T16:07:42.157 回答
1
user=> (defn in-nested? [thing elt]
  #_=>   (if (vector? thing) 
  #_=>       (boolean (some #(in-nested? % elt) thing)) 
  #_=>       (= thing elt)))
#'user/in-nested?

user=> (def data [[[[:a 20] [:b :30]] [[:c 20] [:d :30]]] [[[:h 20] [:g :30]] [[:f 20] [:e :30]]]])
#'user/data

user=> (in-nested? data :a)
true
user=> (in-nested? data :c)
true
user=> (in-nested? data :z)
false
user=> (in-nested? data 20)
true
user=> (in-nested? data 40)
false
于 2013-04-27T15:21:48.733 回答