Question

Take a function which inputs a set, set of sets, collection, nested vector with collections buried within, etc. So, the inputs sometimes are not of the same type. How would one go about converting such input into a nested vector structure? In the first case of just a set, I would use

(into [] #{1 2 3 4})

converting the into into a vector. But the case of sets within sets, I am unable to output nested vectors, i.e.

#{1 2 3 #{1 2 3}}

Similarly, I might have an input such as

[1 2 3 (4 5 6)]

and I want to output

[1 2 3 [4 5 6]]

The idea is that sometimes I need to go within the depth and pick out a collection or set to turn into a vector. Is it possible to have a function, which in general can handle the many different structural inputs and output a nested vector structure. Namely can a function generalize the aforementioned examples? I simplified the samples somewhat, for instance I might have inputs such as

[[[1 2 3 4] [#{1 2 3 4} 2 3 4] [(1 2 3 4) 2 3 4]]]

To give more insight into the function I am trying to work on consider the function C from the language R. The importance of this function lies in the importance of vector structures within statistics/data analysis.

Was it helpful?

Solution

user=> (use 'clojure.walk)
user=> (clojure.walk/postwalk (fn [e] (if (coll? e) (vec e) e)) '(1 2 3 #{4 5 6 (7 8 9)}))
[1 2 3 [4 5 6 [7 8 9]]]

OTHER TIPS

a naive reduce implementation:

(defn to-vectors [c]
  (reduce #(conj %1 (if (coll? %2) (to-vectors %2) %2))
          [] c))

user=> (to-vectors '[[[1 2 3 4] [#{1 2 3 4} 2 3 4] [(1 2 3 4) 2 3 4]]])  
[[[1 2 3 4] [[1 2 3 4] 2 3 4] [[1 2 3 4] 2 3 4]]]
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top