【问题标题】:Rotate list by the input number按输入编号轮换列表
【发布时间】:2021-12-13 12:59:33
【问题描述】:

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

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

【问题讨论】:

  • 你尝试了什么,什么不起作用?
  • 从列表的前面取一个元素很容易,但把它放在后面很难。从后面取出一个元素很难,但把它放回前面很容易。
  • 提示:向左旋转 n 个位置,与使用 m 向右旋转 mn 个位置相同要旋转的列表的长度。
  • 我明白了!非常感谢你们!
  • 如果你想同时旋转1个以上的位置,使用splitAt :: Int -> [a] -> ([a],[a])怎么样?

标签: list haskell recursion


【解决方案1】:

解决此问题的一种简单方法是将向左旋转 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)

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

【讨论】:

    猜你喜欢
    • 2014-11-05
    • 1970-01-01
    • 1970-01-01
    • 2020-08-19
    • 1970-01-01
    • 1970-01-01
    • 2015-05-18
    • 2015-04-30
    • 1970-01-01
    相关资源
    最近更新 更多