Skip to content

Instantly share code, notes, and snippets.

@deltamualpha
Created March 22, 2013 03:49
Show Gist options
  • Save deltamualpha/5218827 to your computer and use it in GitHub Desktop.
Save deltamualpha/5218827 to your computer and use it in GitHub Desktop.
I suck at clojure.
(defn magic [row]
(if (map? (first row)) (for [x row] (into [] (flatten (seq x)))) (into [] x)))
(defn collapser [incoming]
(reduce (fn [a b] (conj a (magic b))) [["header" "information"]] (remove nil? incoming)))
;for an input like
;([:a a :b b] nil nil [{:c c, :d d} {:e e, :f f}] nil [:a g :b h]) =>
;[["test" "two"] [:a "a" :b "b"] ([:c "c" :d "d"] [:e "e" :f "f"]) [:a "g" :b "h"]]
;but what I want is
;[["test" "two"] [:a "a" :b "b"] [:c "c" :d "d"] [:e "e" :f "f"] [:a "g" :b "h"]]
@jeremyheiler
Copy link

Will this work for you? It assumes that there will always be "two pairs" of some kind in sets of two.

(def input '([:a "a" :b "b"]
               nil
               nil
               [{:c "c" :d "d"} {:e "e" :f "f"}]
               nil
               [:a "g" :b "h"]))

;; Assumes that coll only contains collections with 4 elements
;; This also means maps with only two key value pairs.
(defn collapse
  [coll]
  (letfn [(f [form] (if (map? form) (seq form) form))]
    (->> coll
         (remove nil?)             ;; Removes all top-level nil values
         (clojure.walk/postwalk f) ;; Converts maps to seq of pairs
         (flatten)                 ;; Flatten all sequential colls
         (partition 4 4)           ;; Create a seq for every 4 values
         (map vec)                 ;; Convert each seq into a vector
         (cons ["foo" "bar"])      ;; Add header information to front
         (vec))))                  ;; Convert entire thing to a vector

In action:

user> (collapse input)
[["foo" "bar"] [:a "a" :b "b"] [:c "c" :d "d"] [:e "e" :f "f"] [:a "g" :b "h"]]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment