Reputation: 1057
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
Upvotes: 0
Views: 385
Reputation: 5766
vector?
returns true
if its argument is a vector (implements IPersistentVector
). [:a :b :c :d]
is a vector. So is [[:a :b] [:c :d]]
. Therefore, calling vector?
on either of them will return true
.
Now, we can say a vector is nested if any of its elements is a vector. We can test for this using some
and the vector?
predicate:
(defn nested-vector? [v]
(some vector? v))
This will test specifically for vectors. However, you might want to take a more general approach that applies to any Sequential
data structure:
(defn nested? [coll]
(some sequential? coll))
Upvotes: 0
Reputation: 91534
checking if any of them are sequential seems close:
user> (every? #(not (sequential? %)) [:a :b :c :d])
true
user> (every? #(not (sequential? %)) [:a :b :c :d [:e]])
false
because all the base collections can be made into sequences, though it may be necessary to also check for Java arrays:
(every? #(not (sequential? %)) [:a :b :c :d (into-array [1 2 3])])
Upvotes: 0