Problem 19

99 Haskell Problems

Problem 19

(**) Rotate a list N places to the left.

Hint: Use the predefined functions length and (++).

Examples:

* (rotate '(a b c d e f g h) 3)
(D E F G H A B C)

* (rotate '(a b c d e f g h) -2)
(G H A B C D E F)

Examples in Haskell:

*Main> rotate ['a','b','c','d','e','f','g','h'] 3
"defghabc"
 
*Main> rotate ['a','b','c','d','e','f','g','h'] (-2)
"ghabcdef"

Solution:

rotate :: [a] -> Int -> [a]
rotate [] _ = []
rotate xs 0 = xs
rotate (x:xs) n 
 | n > 0 = rotate (xs++[x]) (n-1)
 | otherwise = rotate (x:xs) (length (x:xs) + n)

The case n < 0 is represented in the otherwise by call rotate with a positive value.

Advertisements