# 99 questions/Solutions/19

### From HaskellWiki

< 99 questions | Solutions(Difference between revisions)

m (new solution using replicate) |
|||

Line 35: | Line 35: | ||

where |
where |
||

nn = n `mod` length xs |
nn = n `mod` length xs |
||

+ | </haskell> |
||

+ | |||

+ | or |
||

+ | |||

+ | <haskell> |
||

+ | rotate xs n = take len $ drop i $ concat $ replicate 2 xs |
||

+ | where len = length xs |
||

+ | i = n `mod` len |
||

</haskell> |
</haskell> |

## Revision as of 22:30, 15 August 2010

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

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

rotate [] _ = [] rotate l 0 = l rotate (x:xs) (n+1) = rotate (xs ++ [x]) n rotate l n = rotate l (length l + n)

There are two separate cases:

- If n > 0, move the first element to the end of the list n times.
- If n < 0, convert the problem to the equivalent problem for n > 0 by adding the list's length to n.

or using cycle:

rotate xs n = take len . drop (n `mod` len) . cycle $ xs where len = length xs

or

rotate xs n = if n >= 0 then drop n xs ++ take n xs else let l = ((length xs) + n) in drop l xs ++ take l xs

or

rotate xs n = drop nn xs ++ take nn xs where nn = n `mod` length xs

or

rotate xs n = take len $ drop i $ concat $ replicate 2 xs where len = length xs i = n `mod` len