Fork me on GitHub
#beginners
<
2016-11-03
>
olegakbarov12:11:03

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"}]
``````

olegakbarov12:11:32

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

olegakbarov12:11:40

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

wgfm13:11:51

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 `:a`s are equal?

wgfm13:11:15

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

dominicm13:11:35

@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]}]`

wgfm13:11:35

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]}]`

wgfm13:11:04

So the :a would be unique in the resulting seq

wgfm13:11:42

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

wgfm13:11:43

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`

wgfm13:11:04

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

wgfm13:11:47

and then reduce each of the partitions

wgfm13:11:37

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`