elm-community / list-extra

Convenience functions for working with List.
http://package.elm-lang.org/packages/elm-community/list-extra/latest
MIT License
135 stars 58 forks source link

add rotateLeft and rotateRight #98

Open pzp1997 opened 6 years ago

pzp1997 commented 6 years ago

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

Qata commented 6 years ago

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

Chadtech commented 6 years ago

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

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

Chadtech commented 6 years ago

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