如何在无限列表上实现旋转功能?

时间:2015-03-23 21:28:35

标签: haskell infinite-loop

我尝试实现rotate函数,它可以使用无限列表。我对infinite lists有疑问。

我的功能是:

cyclicRotation:: Int -> [a] -> [a]
cyclicRotation num ls = (drop ((length ls) - (mod num (length ls)))  ls) ++ ( take ((length ls) -(mod num (length ls))) ls)

我尝试将我的功能用作:

take 2 (cyclicRotation 9 [1..])

我希望得到[10, 11]

1 个答案:

答案 0 :(得分:4)

为了使用无限列表,您需要避免使用非延迟的评估函数(例如长度)。简单的示例实现是:

rotate :: Int -> [a] -> [a]
rotate _ [] = []
rotate 0 list = list
rotate n (x:xs) = rotate (n-1) (xs ++ [x])

此处(xs ++ [x])甚至可用于无限列表,因为++是懒惰的。