Rotate a list in Haskell
For completeness's sake, a version that works with both empty and infinite lists.
rotate :: Int -> [a] -> [a]
rotate _ [] = []
rotate n xs = zipWith const (drop n (cycle xs)) xs
Then
Prelude> rotate 2 [1..5]
[3,4,5,1,2]
Why make it complicated?
rotate n xs = bs ++ as where (as, bs) = splitAt n xs
A simple solution using the cycle
function, which creates an infinite repetition of the input list:
rotate :: Int -> [a] -> [a]
rotate n xs = take (length xs) (drop n (cycle xs))
then
> rotate 2 ["#","@","#","#"]
["#","#","#","@"].