How to define a rotates function

后端 未结 8 2010
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-11 14:47

How to define a rotates function that generates all rotations of the given list?

For example: rotates [1,2,3,4] =[[1,2,3,4],[2,3,4,1],[3,4,1,2],[4,1,2,3]]

8条回答
  •  渐次进展
    2021-01-11 15:19

    shift (x:xs)  =  xs ++ [x]
    rotates xs    =  take (length xs) $ iterate shift xs
    

    iterate f x returns the stream ("infinite list") [x, f x, f (f x), ...]. There are n rotations of an n-element list, so we take the first n of them.

提交回复
热议问题