list-extra
list-extra copied to clipboard
add rotateLeft and rotateRight
I think it would be good to add functions for rotating a matrix by 90 degrees. Here are possible implementations of the functions:
rotateLeft : List (List a) -> List (List a)
rotateLeft =
List.reverse << transpose
rotateRight : List (List a) -> List (List a)
rotateRight listOfLists =
List.foldl (List.map2 (::)) (List.repeat (rowsLength listOfLists) []) listOfLists
I omitted the helpers here for brevity, but made an Ellie with the full implementations and tests https://ellie-app.com/cyQ6L4kgta1/2. (Note that transpose and rowsLength are functions that I wrote that are already part of List.Extra.)
As for my use case, I was making a Tic-Tac-Toe game last night for fun and it turns out that having either of these functions make checking for a win very easy. Check it out! https://ellie-app.com/3zjbyv2y6a1/2 (scroll down to the checkStatus function).
One other thing worth discussing is the names. I do not think that the current ones make it clear that we are working with matrices and not 1-dimensional lists. For example, rotateRight [1, 2, 3, 4] might be misunderstood to be [4, 1, 2, 3] (which might also be a helpful function?).
I came here looking for discussion of a 1-dimensional rotate function, so it'd definitely be helpful if that was also included!
Nice @pzp1997 ! Looks good to me. Lets do it
But regarding the name, I can also see how its confusing. Maybe rotateMatrixRight instead?
@Qata A 1-dimensional rotate also sounds good. Someone just needs to make the case for it, show how it helps in practice, and then a PR.