Sparsely populated multidimensional vector in clojure? -


i'm trying create sparsely populated multidimensional vector in clojure, i'm coming against limits of knowledge.

i have collection x i'm iterating over, , want create multidimensional vector of size (count x) (count x). of cells empty, @ each point x , y axes match (e.g., (1 1), (2 2), (3 3), etc.), need run function see if value should put in space.

in procedural language, like:

for (i = 0; < length(x); i++) {     (j = 0; j < length(x); j++) {         if (i == j && testreturnstrue(x[i])) {             table[i][j] = (list x[i])         }         else {             table[i][j] = ()         }     } } 

but can't wrap head around how done in clojure. tried using nested comprehensions , nested loop-recur structures can't either work.

alternatively, create mutable table right sizes, initialize empty lists, , set values check each element in x, i'd keep table immutable if possible.

nested fors how it:

(def x [:a :b :c :d]) (vec (for [i (range (count x))]        (vec (for [j (range (count x))]               (if (and (= j) (identity (x i)))                 [(x i)]                 []))))) => [[[:a] [] [] []] [[] [:b] [] []] [[] [] [:c] []] [[] [] [] [:d]]] 

(identity (x i)) stand-in kind of test.

edit: mentioned in other answers, if structure remains sparsely populated, hash-map better choice. assuming populating empty portions in later computations.


Comments