Hi,

I have a peculiar sequence of nested maps which have the following structure -

{:a 1 :b 1 :c []}

The keys :a & :b always have scalar values but the :c key can have
either an empty vector or a vector of maps of the same kind. For
example -

{:a 1 :b 1 :c [{:a 1 :b 1 :c [{:a 1 :b 1 :c []}]} {:a 1 :b 1 :c []}]}

The task is to write a function `flatten-maps` which will take a
vector of such maps and will return a sequence of maps with only the
:a & :b keys.

Example -

(def data [{:a 1 :b 1 :c [{:a 1 :b 1 :c [{:a 1 :b 1 :c []}]} {:a 1 :b
1 :c []}]} {:a 1 :b 1 :c [{:a 1 :b 1 :c [{:a 1 :b 1 :c []}]} {:a 1 :b
1 :c []}]}])

(flatten-maps data)
;=> ({:a 1, :b 1} {:a 1, :b 1} {:a 1, :b 1} {:a 1, :b 1} {:a 1, :b 1}
{:a 1, :b 1} {:a 1, :b 1} {:a 1, :b 1})

My solution -

(defn flatten-maps
  [ms]
  (if-let [ms (seq ms)]
    (reduce (fn [v m]
              (if (seq (:c m))
                (concat (conj v (dissoc m :c))
                        (flatten-maps (:c m)))
                (conj v (dissoc m :c))))
            []
            ms)
    []))

The goal is to write something which is fast using idiomatic Clojure.

This is just a fun exercise, nothing serious :)

Regards,
BG

-- 
Baishampayan Ghose
b.ghose at gmail.com

-- 
You received this message because you are subscribed to the Google
Groups "Clojure" group.
To post to this group, send email to clojure@googlegroups.com
Note that posts from new members are moderated - please be patient with your 
first post.
To unsubscribe from this group, send email to
clojure+unsubscr...@googlegroups.com
For more options, visit this group at
http://groups.google.com/group/clojure?hl=en

Reply via email to