Skip to content

Instantly share code, notes, and snippets.

@bdesham
Created July 6, 2011 16:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bdesham/1067736 to your computer and use it in GitHub Desktop.
Save bdesham/1067736 to your computer and use it in GitHub Desktop.
Transpose a matrix in Clojure
(defn square-matrix?
[mat]
(apply =
(count mat)
(for [r mat] (count r))))
(defn transpose
[mat]
{:pre [(square-matrix? mat)]}
(loop [res [],
mat mat]
(if (empty? (first mat))
res
(recur (conj res
(vec (for [r mat] (first r))))
(for [r mat] (rest r))))))
@bdesham
Copy link
Author

bdesham commented Jul 6, 2011

Or even this:

(defn square-matrix?
  [mat]
  (apply =
         (count mat)
         (for [r mat] (count r))))

(defn transpose
  [mat]
  {:pre [(square-matrix? mat)]}
  (apply map vector mat))

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