Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/haskell/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
List 围绕索引旋转列表_List_Haskell - Fatal编程技术网

List 围绕索引旋转列表

List 围绕索引旋转列表,list,haskell,List,Haskell,我有一个列表,比如说[1,2,3,4,5],我必须在索引处旋转列表 例如: 旋转2[1,2,3,4,5]给出[3,4,5,1,2] 通过在线研究,我遇到了循环函数,它解决了当你放下列表时会丢失列表的问题,但我觉得如果我能从自己的工作解决方案中获得更多的理解,即使它的效率不如库函数。我的工作方案如下: rotate :: Int -> [a] -> [a] rotate _ [] = [] rotate n l = take (length l) $ drop n (cycle l)

我有一个列表,比如说[1,2,3,4,5],我必须在索引处旋转列表

例如:

旋转2[1,2,3,4,5]给出[3,4,5,1,2]

通过在线研究,我遇到了循环函数,它解决了当你放下列表时会丢失列表的问题,但我觉得如果我能从自己的工作解决方案中获得更多的理解,即使它的效率不如库函数。我的工作方案如下:

rotate :: Int -> [a] -> [a]
rotate _ [] = []
rotate n l  = take (length l) $ drop n (cycle l)
在没有代码的情况下,您能否建议实现此解决方案的其他方法,以便我可以尝试一下这些方法?由于我没有想法,现在我看到了这样做的方式


干杯

既然这里已经存在一个带有代码的解决方案,我将发布另一个版本:

rotate :: Int -> [a] -> [a]
rotate n [] = []
rotate n xs = xs2 ++ xs1
    where (xs1, xs2) = splitAt (n `rem` length xs) xs
一些测试:

main = do
    print $ rotate 0 [1..5] -- [1,2,3,4,5]
    print $ rotate 2 [1..5] -- [3,4,5,1,2]
    print $ rotate 5 [1..5] -- [1,2,3,4,5]
    print $ rotate 7 [1..5] -- [3,4,5,1,2]

因为这里已经存在一个带有代码的解决方案,我将发布另一个版本:

rotate :: Int -> [a] -> [a]
rotate n [] = []
rotate n xs = xs2 ++ xs1
    where (xs1, xs2) = splitAt (n `rem` length xs) xs
一些测试:

main = do
    print $ rotate 0 [1..5] -- [1,2,3,4,5]
    print $ rotate 2 [1..5] -- [3,4,5,1,2]
    print $ rotate 5 [1..5] -- [1,2,3,4,5]
    print $ rotate 7 [1..5] -- [3,4,5,1,2]
您可以简单地执行以下操作:

rotate n l  = drop n l ++ take n l 
要实现同样的效果,无需循环。

您只需执行以下操作:

rotate n l  = drop n l ++ take n l 

无需循环即可实现同样的效果。

那么简单的解决方案呢

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

…那么简单的解决方案呢

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

请参阅splitAt函数。请参阅splitAt函数。虽然我不想要编码的解决方案,但这比循环更有意义。谢谢虽然我不想要一个编码的解决方案,但这比循环更有意义。谢谢