Search code examples
clojure

How to transpose a nested vector in clojure


I have the following variable

 (def a [[1 2] [3 4] [5 6]])

and want to return

[[1 3 5][2 4 6]]

and if input is [[1 2] [3 4] [5 6] [7 8 9]] then the required result is

[[1 3 5 7] [2 4 6 8] [9]]

How to do it in clojure?


Solution

  • I like ifett's implementation, though it seems weird to use reduce-kv to build a vector that could be easily build with map/mapv.

    So, here is how I would've done it:

    (defn transpose [v]
      (mapv (fn [ind]
              (mapv #(get % ind)
                    (filter #(contains? % ind) v)))
            (->> (map count v)
                 (apply max)
                 range)))