Reputation: 21
when I try to input the function below. I come up with how to rotate the func when the input is positive, however, when it is negative, I don't how to solve it. The code is below:
-- rotate : Takes a list, and a value, and rotates the list around
-- by the number of elements indicated
rotate :: [a] -> Int -> [a]
rotate ls m = case ls of
[] -> []
x:xs
| m == 0 -> x:xs
| otherwise -> rotate (xs ++ [x]) (m-1)
Upvotes: 1
Views: 163
Reputation: 477598
A simple way to solve this is by seeing a rotation of m places to the left as a rotation of m mod n items to the right, with n the length of the list to rotate.
We thus can implement this as:
rotate :: [a] -> Int -> [a]
rotate xs m
| m < 0 = rotate xs (m `mod` length xs)
rotate ls m = case ls of
[] -> []
x:xs
| m == 0 -> x:xs
| otherwise -> rotate (xs ++ [x]) (m-1)
It might also be better to look for a way to rotate more efficiently than rotating one position at a time.
Upvotes: 1