How to define a rotates function

后端 未结 8 1994
佛祖请我去吃肉
佛祖请我去吃肉 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-11 15:17

    I think it will be something like this (I don't have ghc right now, so I couldn't try it)

    shift (x:xs) = xs ++ [x]
    
    rotateHelper xs 0 = []
    rotateHelper xs n = xs : (rotateHelper (shift xs) (n - 1))
    
    rotate xs = rotateHelper xs  (length xs)
    

提交回复
热议问题