【发布时间】: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])怎么样?