简体   繁体   English

Haskell 旋转列表列表

[英]Haskell rotate list of lists

I'm trying to implement the following function in Haskell, its a recursive traversal that receives an Int and a list of lists [[Int]] and shifts the elements of the inner lists to the right without altering the size of the lists.我正在尝试在 Haskell 中实现以下 function,它是一个递归遍历,它接收一个 Int 和一个列表列表 [[Int]] 并将内部列表的元素向右移动而不改变列表的大小。 I was able to get a list with the numbers in the right order but I couldn't insert them back into their proper sublists.我能够以正确的顺序获得一个包含数字的列表,但我无法将它们重新插入到正确的子列表中。

shift_right::Int->[[Int]]->[[Int]]

example #1:示例#1:

shift_right 1 [[1,2,3],[4,5,6]] => [[6,1,2],[3,4,5]]

example #2:示例#2:

shift_right 3 [[],[1],[2,3],[4,5,6]] => [[],[4],[5,6],[1,2,3]]

Assuming that the empty lists only appear at the beginning and never in the middle then one approach could be, first to find a way to make a single rotation and then to repeat the same action n times for n rotations.假设空列表只出现在开头而不出现在中间,那么一种方法可能是,首先找到一种方法进行一次旋转,然后重复相同的动作n次旋转n次。 I think we can use mapAccumL for this purpose.我认为我们可以为此目的使用mapAccumL

m = [[],[1],[2,3],[4,5,6]]
s l = es ++ (rem ++ ls) : lss
      where
      (rem, (ls:lss)) = mapAccumL shifter [] fs
      shifter a bs    = ([last bs], a ++ (init bs))
      (es,fs)         = span (== []) l              -- split empties and fulls

λ> s m
[[],[6],[1,2],[3,4,5]]

λ> s [[],[6],[1,2],[3,4,5]] -- carry from previous answer
[[],[5],[6,1],[2,3,4]]

λ> s [[],[5],[6,1],[2,3,4]] -- carry from previous answer
[[],[4],[5,6],[1,2,3]]

So now... since you show no attempt at all, it is your duty to come up with a code that invokes this function (or a part of this function) n times for n rotations Hint: preferablly without concatenating the empties.所以现在......既然你根本没有尝试,你有责任想出一个代码来调用这个 function (或这个函数的一部分) nn轮换提示:最好不要连接空的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM