list-extra icon indicating copy to clipboard operation
list-extra copied to clipboard

add rotateLeft and rotateRight

Open pzp1997 opened this issue 7 years ago • 3 comments
trafficstars

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?).

pzp1997 avatar May 01 '18 15:05 pzp1997

I came here looking for discussion of a 1-dimensional rotate function, so it'd definitely be helpful if that was also included!

Qata avatar Jul 12 '18 05:07 Qata

Nice @pzp1997 ! Looks good to me. Lets do it

But regarding the name, I can also see how its confusing. Maybe rotateMatrixRight instead?

Chadtech avatar Jul 18 '18 16:07 Chadtech

@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.

Chadtech avatar Jul 18 '18 16:07 Chadtech