I have a function to rotate the list:
rotate :: [a] -> [a] rotate [] = [] rotate (x:xs) = xs ++ [x]
Now I want a function that gives a list with every possible rotation of the final list:
rotateAll :: [a] -> [[a]]
In an imperative language, I would do something like (in pseudocode)
for i = 1 to length of list append list to rotateList list = rotate(list)
Of course, rational thinking probably does not help me find a functional solution to this problem. I am looking for some tips on how to deal with this.
Additional thoughts:
To solve this problem, I have two questions. First I need to rotate the list many times and collect each result into a list. So the first solution is to do something like
rotateAll xs = [xs (rotate xs) (rotate (rotate xs)) (rotate (rotate (rotate xs))) ...]
Of course, I do not know how many times to do this. I would be pleased to do this endlessly, and then use take (length xs) to get the finite number of lists I wish. This actually demonstrates a second problem: determining when to stop. I don't know if using take most efficient or elegant way to solve a problem, but it occurred to me when I was typing this and should work.
Addendum: Now that I have found two solutions on my own or with tips. I am pleased to welcome any other solutions that are faster or use different approaches. Thanks!
source share