Skip to main content

Command Palette

Search for a command to run...

Transpose a Matrix in Clojure

Updated
2 min read
Transpose a Matrix in Clojure

Imagine rows of letters, numbers, and Greek letters:

[[:a :b]
 [:1 :2]
 [:alpha :beta]]

Now, you want to transpose them. You started with a vector of vectors. Clojure's map function is pretty amazing::

  • (map f)

  • (map f coll)

  • (map f c1 c2)

  • (map f c1 c2 c3)

  • (map f c1 c2 c3 & colls)

Returns a lazy sequence consisting of the result of applying f to the set of first items of each coll, followed by applying f to the set of second items in each coll, until any one of the colls is exhausted. Any remaining items in other colls are ignored. Function f should accept number-of-colls arguments. Returns a transducer when no collection is provided.

Normally, I think of this arity of map: (map f coll). In your case, you have three collections, so you'll make use of (map f c1 c2 c3). You want to stick with vectors, so you'll use mapv, which has the same semantics.

If you ignore the outer vector, you can use mapv with vector:

(mapv vector [:a :b] [:1 :2] [:alpha :beta])
;;=> [[:a :1 :alpha]
;;    [:b :2 :beta]]

You don’t have to omit the outer vector thanks to the magic of apply, which allows you to pass a collection of arguments to a function that wants individual arguments:

(apply mapv vector [[:a :b] [:1 :2] [:alpha :beta]])
;;=> [[:a :1 :alpha]
;;    [:b :2 :beta]]

This is amazing.