I have a list a
defined,
let a = ["#","@","#","#"]
How can I rotate the @
two spaces, so that it ends up like this?
["#","#","#","@"]
I thought this might work,
map last init a
but maybe the syntax has to be different, because map can only work with one function?
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]
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 ["#","@","#","#"] ["#","#","#","@"].
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With