首页 > 解决方案 > 按输入编号轮换列表

问题描述

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

-- 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)

标签: listhaskellrecursion

解决方案


解决此问题的一种简单方法是将向左旋转m个位置作为向右旋转m mod n 个项目,其中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)

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


推荐阅读