0

Is there a way in Clojure to test a vector and see if it's nested, i.e. a way to test [:a :b :c :d] vs. [[:a :b] [:c :d]]?

I've tried the test

(vector? [:a :b :c :d])
 true

but it remains true for nested vectors as well,

(vector? [[:a :b] [:c :d]])
 true
4

2 回答 2

0

vector?true如果它的参数是一个向量(实现IPersistentVector), 则返回。[:a :b :c :d]是一个向量。也是如此[[:a :b] [:c :d]]。因此,调用vector?其中任何一个都将返回true

现在,如果向量的任何元素是向量,我们就可以说向量是嵌套的。some我们可以使用和vector?谓词对此进行测试:

(defn nested-vector? [v]
  (some vector? v))

这将专门针对向量进行测试。但是,您可能希望采用适用于任何Sequential数据结构的更通用的方法:

(defn nested? [coll]
  (some sequential? coll))
于 2013-11-23T16:42:15.773 回答
0

检查它们中的任何一个是否是连续的似乎很接近:

user> (every? #(not (sequential? %)) [:a :b :c :d])
true
user> (every? #(not (sequential? %)) [:a :b :c :d [:e]])
false

因为所有基本集合都可以组成序列,尽管可能还需要检查 Java 数组:

(every? #(not (sequential? %)) [:a :b :c :d (into-array [1 2 3])])
于 2013-11-23T05:28:07.043 回答