10

I'm new to Clojure and functional programming in general. I'm at a loss in how to handle this in a functional way.

I have the following matrix:

(def matrix [[\a \b \c]
             [\d \e \f]
             [\g \h \i]])

I want to transform it into something like this (rotate counterclockwise):

((\a \d \g)
 (\b \e \h)
 (\c \f \i ))

I've hacked up this bit that gives me the elements in the correct order. If I could collect the data in a string this way I could then split it up with partition. However I'm pretty sure doseq is the wrong path:

(doseq [i [0 1 2]]
  (doseq [row matrix]
    (println (get (vec row) i))))

I've dabbled with nested map calls but keep getting stuck with that. What's the correct way to build up a string in Clojure or handle this in an even better way?

4 Answers 4

34

What you're trying to achieve sounds like transpose. I'd suggest

(apply map list matrix)
; => ((\a \d \g) (\b \e \h) (\c \f \i))

What does it do?

(apply map list '((\a \b \c) (\d \e \f) (\g \h \i)))

is equivalent to

(map list '(\a \b \c) '(\d \e \f) '(\g \h \i))

which takes first elements of each of the three lists, calls list on them, then takes second elements, calls list on them... An returns a sequence of all lists which were generated this way.

A couple more examples of both apply and map can be found on ClojureDocs.

0
10

Taking the matrix transposition solution directly from rosettacode:

(vec (apply map vector matrix))

To see what is going on consider:

(map vector [\a \b \c] [\d \e \f] [\g \h \i])

This will work nicely with arbitrary matrix dimensions although it is not good for significant number crunching, for that you would want to consider using a java based matrix manipulation library from Clojure.

0
5

You can use core.matrix to do these kind of matrix manipulations very easily. In particular, there is already a transpose function that does exactly what you want:

Example:

(use 'clojure.core.matrix)

(def matrix [[\a \b \c]
             [\d \e \f]
             [\g \h \i]])

(transpose matrix)
=> [[\a \d \g] 
    [\b \e \h] 
    [\c \f \i]]
2

Here's one way:

(def transposed-matrix (apply map list matrix))
;=> ((\a \d \g) (\b \e \h) (\c \f \i))

(doseq [row transposed-matrix] 
  (doall (map println row)))

That produces the same output as your original (printing the columns of matrix).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.