Fork me on GitHub

Trying to create a nested vector (that represents tree) from a map. Any tip here?

;; Input 
   {:a {:kids [:b :c]}
    :b {:text "b"}
    :c {:kids [:d :e]}
    :d {:text "d"}
    :e {:kids [:f]}
    :f {:text "f"}
    :g {:text “g”}}

;; Expected result
[[{:text "b"} 
  [{:text "d"} 
   [{:text "f"}]]] 
 {:text "g"}]


Pretty sure i gotta use recur but can’t figure out how … :white_frowning_face:


The main idea is to replace keywords in :kids with values from the map


Say, I have a seq of maps. Each map has two key/value pairs, :a and :b. Assume the seq is sorted by the value of :a in the maps. Is there some kind of reduce operation that allows me to get a seq of maps with keys :a and :bs, where the value of :bs is a seq of all :b values in the original map where the :as are equal?


Or do I have to write it myself with my own reduce function?


@wgfm So you want to go from [{:a 1 b 1} {:a 1 :b 2}] to [{:a 1 :bs [1 2]} {:a 2 :bs [1 2]}]


Close, but rather from [{:a 1 :b 1} {:a 1 :b 2} {:a 2 :b 1}] to [{:a 1 :bs [1 2]} {:a 2 :bs [1]}]


So the :a would be unique in the resulting seq


I need such a thing a lot, and I always end up writing the solution myself in different ways, but it’s never a really satisfying solution


such as grouping by :a and going from there - but that’s more costly than it needs to be, since the seq is sorted by :a


I think I found what i’m looking for: partition-by


and then reduce each of the partitions


Thanks for your time, though, @dominicm 🙂


I feel like there aught to be a perfect name for this concept, but I just don't know it. Can anyone help me out?

;; If I want to traverse a grid like this I can do it by column or by row
(def xs [[1 2 3]
         [1 2 3]
         [1 2 3]])

;; If I put this in an options map for a function, what can I call it?
(defn traverse [xs & {:keys [???] :or {??? :row}}]
  (case ???
    :row (flatten xs)
    :col (apply mapcat vector xs)))

(traverse xs :??? :row)

(traverse xs :??? :col)


@madstap maybe instead of :row, :col, maybe :breadth-first :depth-first, and then :??? could be :traversal-type or :direction? It definitely feels like there should be a name for that! Good luck 😉


I'm talking about excel columns and rows, so I think that the :col or :row should be kept. I'm between two options at the moment.

(traverse xs :direction :row)
(traverse xs :by :row)


cool, fwiw, I like :by


Yeah, I went with that. I just still feel like there's some word for this, like "arity".


I am receiving a Null Pointer Exception for one of the Clojure for the Brave and True code samples. Any help would certainly be appreciated:


The answer was posted in the stackoverflow board if you are interested. It was due to a key mismatch in the handover to the next function, so the next function received nil and produced the NPE.