您似乎更喜欢我们修复您的代码而不是重新开始,所以让我们看看您的代码。首先,主列表砍:
reverse (take i (reverse xs)) ++ reverse (drop i (reverse xs))
现在从列表末尾reverse (take i (reverse xs))
获取i
元素,但是您将列表反转两次以实现此目的,这样做会更好
drop (length xs - i) xs
。同样,您可以实现reverse (drop i (reverse xs)))
为take (length xs - i) xs
. 这给了我们
drop (length xs - i) xs ++ take (length xs - i) xs
现在您的代码\i->[1..n]<=n
没有意义,因为它将列表[1..n]
与进行比较n
,这是行不通的。我认为您正在尝试创建一个i
从
1
to运行的循环n
,这是一个不错的计划。让我们使用列表推导来获得我们想要的:
[drop (length xs - i) xs ++ take (length xs - i) xs | i <- [1 .. length xs], i <= n]
但是现在我们从 1 运行到列表的长度,但丢弃了上面的数字n
,这样写会更好
[drop (length xs - i) xs ++ take (length xs - i) xs | i <- [1..n]]
这确实允许n
超过length xs
,但我看不出有什么大问题,我们可以先检查一下。
现在请注意,我们只i
在 form(length xs - i)
中使用,实际上我们重新计算
length xs
的次数比我们应该的要多得多,所以不要让run i
from 1
ton
和 using
length xs - i
,我们为什么不直接运行 from to :j=length xs -i
j
length xs
length xs - n
[drop j xs ++ take j xs | j <- [length xs,length xs - 1 .. length xs - n]]
这有效,因为例如[6,5..1] == [6,5,4,3,2,1]
这样做会更整洁
let l = length xs in
[drop j xs ++ take j xs | j <- [l,l - 1 .. l - n]]
或者你可能take
比你更喜欢做算术,所以我们可以使用:
let l = length xs in
take n [drop j xs ++ take j xs | j <- [l,l - 1 .. 0]]
这还有一个额外的好处,就是阻止你做太多事情,当你回到起点时阻止你。
我会将您的功能从generatingListforRightShifting
to重命名rotationsR
为
rotationsR n xs = let l = length xs in
take n [drop j xs ++ take j xs | j <- [l,l - 1 ..]]
这给了rotationsR 6 [1..4] == [[1,2,3,4],[4,1,2,3],[3,4,1,2],[2,3,4,1],[1,2,3,4]]
.
左旋转看起来更简单:
rotationsL n xs = take n [drop j xs ++ take j xs | j <- [0..length xs]]
题外话:我忍不住,对不起,我又开始了。
我仍然不喜欢每次都丢掉和拿走所有的东西,我宁愿弹出无限多的副本xs
(第一个:cycle xs
tails
rotationsL' n xs = let l = length xs in take n 。地图(取 l)。尾巴。周期 $xs
由于惰性评估,只有有限的cycle xs
ever 被计算,但是这个可以运行和运行:rotationsL' 10 [1..4]
给你:
[[1,2,3,4],[2,3,4,1],[3,4,1,2],[4,1,2,3],[1,2,3,4],[2,3,4,1],[3,4,1,2],[4,1,2,3],[1,2,3,4],[2,3,4,1]]
以这种方式进行正确的循环也很好,但它不起作用,因为我需要从无限列表的末尾开始并返回。让我们重用你的反向,采取你需要的,再次反向技巧,虽然:
rotationsR' n xs = let l = length xs in
take n . map (reverse.take l) . tails . cycle . reverse $ xs
题外话:如果您宁愿更贴近原始代码,您可以这样做
generatingListforRightShifting n xs =
[reverse (take i (reverse xs)) ++ reverse (drop i (reverse xs)) | i <- [1..n]]