按输入的数字旋转列表



当我尝试输入下面的函数时。我想出了当输入为正时如何旋转函数,然而,当输入为负时,我不知道如何求解它。代码如下:

-- rotate : Takes a list, and a value, and rotates the list around
-- by the number of elements indicated
rotate :: [a] -> Int -> [a]
rotate ls m = case ls of 
[] -> [] 
x:xs 
| m == 0 -> x:xs
| otherwise -> rotate (xs ++ [x]) (m-1)

解决这个问题的一个简单方法是将m位置旋转到左边,作为mmodn项到右边的旋转,其中n是要旋转的列表的长度。

因此我们可以这样实现:

rotate :: [a] -> Int -> [a]
rotate xs m
|m < 0 = rotate xs (m `mod` length xs)
rotate ls m = case ls of 
[] -> [] 
x:xs 
| m == 0 -> x:xs
| otherwise -> rotate (xs ++ [x]) (m-1)

寻找一种比一次旋转一个位置更有效的方法可能会更好。

最新更新