Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rotate a matrix in Haskell

Tags:

haskell

I have this type Mat a = [[a]] to represent a matrix in haskell. I have to write a function which rotate a matrix, for e.g [[1,2,3],[0,4,5],[0,0,6]] will become [[3,5,6],[2,4,0],[1,0,0]] so I made this:

rotateLeft :: Mat a->Mat a
rotateLeft [[]] = []
rotateLeft (h:t) = (map last (h:t)):(rotateLeft (map init (h:t)))

but the output is

[[3,5,6],[2,4,0],[1,0,0],[*** Exception: Prelude.last: empty list

I don't know what to put in the base case to avoid this exception. Apreciate any help.

like image 634
paulo_ferreira Avatar asked Dec 06 '22 19:12

paulo_ferreira


2 Answers

I'm an old man in a hurry. I'd do it like this (importing Data.List)

rotl :: [[x]] -> [[x]]
rotl = transpose . map reverse
like image 140
pigworker Avatar answered Dec 09 '22 14:12

pigworker


I think the simplest solution would be:

import Data.List

rotateLeft :: [[a]] -> [[a]]
rotateLeft = reverse . transpose

rotateRight :: [[a]] -> [[a]]
rotateRight = transpose . reverse

Data.List is a standard module.

transpose slices rows into columns, which is almost like rotating, but leaves the columns in the wrong order, so we just reverse them.

like image 42
okdewit Avatar answered Dec 09 '22 14:12

okdewit