matrixrotationschemeracketr6rs

Rotating a matrix, why isn't it working as a function, yet it does in line command?


A way to rotate a matrix is by getting it's transpose and then reversing all the rows. I've got around it with two functions, map (which returns the transpose) and reverse (completing a 90° rotation), in console I do the following:

(reverse (apply map list (list (list 1 2 3 4) (list 5 6 7 8) (list 9 10 11 12) (list 13 14 15 16)) ) )

 Result:  {{4 8 12 16} {3 7 11 15} {2 6 10 14} {1 5 9 13}}

Which is right, yet when I made a function, it doesn't work.

(define (transpose2 matriz)
      (reverse (apply map list matriz))

Then doing:

> (transpose2 (list (list 1 2 3 4) (list 5 6 7 8) (list 9 10 11 12) (list 13 14 15) ) )

It just throws an error:

mcar: contract violation expected: mpair? given: ()

I've tried importing (srfi :41) (I am working on r6rs also) but it isn't working either. This function works for a 3 x 3 matrix though.

How can I fix this?


Solution

  • Your input was incorrect.

    (transpose2 (list (list 1 2 3 4) 
                      (list 5 6 7 8) 
                      (list 9 10 11 12) 
                      (list 13 14 15))) ;; here are only 3 elements while in the others 4!
    
    (transpose2 (list (list 1 2 3 4) 
                      (list 5 6 7 8) 
                      (list 9 10 11 12) 
                      (list 13 14 15 16))) ;; this works flawlessly - you just forgot 16 before!
    

    DrRacket gives the error:

    map: all lists must have same size; arguments were: #<procedure:list> '(1 2 3 4) '(5 6 7 8) '(9 10 11 12) '(13 14 15)
    

    What kind of a Scheme interpreter you were using?

    #lang racket
    
    (define m (list (list 1 2 3 4)
                    (list 5 6 7 8)
                    (list 9 10 11 12)
                    (list 13 14 15 16)))
    
    (define (transpose2 mat)
      (reverse (apply map list mat)))
    
    (reverse (apply map list m))
    (transpose2 m)
    
    ;; both give:
    ;; '((4 8 12 16) (3 7 11 15) (2 6 10 14) (1 5 9 13))