list - 按输入编号轮换列表
问题描述
当我尝试输入下面的函数时。当输入为正时,我想出了如何旋转函数,但是,当输入为负时,我不知道如何解决它。代码如下:
-- 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个位置作为向右旋转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)
寻找一种比一次旋转一个位置更有效地旋转的方法也可能更好。
推荐阅读
- java - 如何更改 ListView 中每个项目的背景颜色?
- azure-cosmosdb - Cosmos DB 中的 Dynamics 365 虚拟实体
- powershell - 在 Powershell 中从字符串中剥离数据
- sql-server - SQL Server 2016 中的外键约束是否可以涉及确定性加密列
- python-3.x - Openpyxl:如何使用可变行合并单元格
- reactjs - React Native:应用程序未更新
- python - 在一个选择语句中使用最小值和最大值(错误输出?)
- javascript - 如何循环遍历对象数组并将对象填充到鼠标悬停函数中?
- reactjs - 即使没有数据,有没有办法设置分页箭头启用?
- google-calendar-api - 作为 G Suite 管理员,获取现有组织单位中“项目”用户列表的电子邮件访问权限