Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rotate a list in Haskell

Tags:

haskell

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?

like image 527
coderkid Avatar asked May 04 '13 20:05

coderkid


2 Answers

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] 
like image 70
dave4420 Avatar answered Sep 18 '22 09:09

dave4420


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 ["#","@","#","#"] ["#","#","#","@"]. 
like image 35
MGwynne Avatar answered Sep 18 '22 09:09

MGwynne