sunspots
sunspots

Reputation: 1057

Testing vectors and nested vectors in Clojure

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

Answers (2)

Nathan Davis
Nathan Davis

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

Arthur Ulfeldt
Arthur Ulfeldt

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

Related Questions