List 如何迭代列表列表
我有一个列表,比如List 如何迭代列表列表,list,haskell,List,Haskell,我有一个列表,比如 [[1, 1, 1, 1], [0, 0, 0, 0], [1, 1, 0, 0], [0, 0, 1, 1]] 长度均匀。就像一个正方形的像素,其中黑色是1,白色是0,就像一个棋盘 我想要一个函数,它将返回4个列表: 第一个列表是2x2,右下角是一个带有[1,1,0,0]的列表 第二个列表是2x2,右上角是一个带有[1,1,0,0]的列表 第三个列表是2x2,左下角是一个带有[0,0,1,1]的列表 第四个列表是2x2,左上角是一个带有[1,1,0,0]的列
[[1, 1, 1, 1],
[0, 0, 0, 0],
[1, 1, 0, 0],
[0, 0, 1, 1]]
长度均匀。就像一个正方形的像素,其中黑色是1,白色是0,就像一个棋盘
我想要一个函数,它将返回4个列表:
第一个列表是2x2,右下角是一个带有[1,1,0,0]的列表
第二个列表是2x2,右上角是一个带有[1,1,0,0]的列表
第三个列表是2x2,左下角是一个带有[0,0,1,1]的列表
第四个列表是2x2,左上角是一个带有[1,1,0,0]的列表
我还不知道怎么做。我希望收到上述4个列表。假设我现在已经了解了您的要求,以下内容对我有效。可能有更复杂的方法可以做到这一点,但这是一个简单的方法,不会太痛苦-关键是编写通用函数,它可以占据偶数长度列表的前/后半部分。然后,您需要的功能就可以简单地从它们中构建:
firstHalf :: [a] -> [a]
firstHalf xs
| odd n = error "list needs to have even length"
| otherwise = take h xs
where n = length xs
h = n `div` 2
secondHalf :: [a] -> [a]
secondHalf xs
| odd n = error "list needs to have even length"
| otherwise = drop h xs
where n = length xs
h = n `div` 2
topLeftCorner :: [[a]] -> [a]
topLeftCorner = concatMap firstHalf . firstHalf
topRightCorner :: [[a]] -> [a]
topRightCorner = concatMap secondHalf . firstHalf
bottomLeftCorner :: [[a]] -> [a]
bottomLeftCorner = concat . reverse . map firstHalf . secondHalf
bottomRightCorner :: [[a]] -> [a]
bottomRightCorner = concat . reverse . map secondHalf . secondHalf
allCorners :: [[a]] -> [[a]]
allCorners board = [bottomRightCorner, topRightCorner, bottomLeftCorner, topLeftCorner] <*> [board]
在函数式编程和一般编程中,处理更复杂问题的最佳方法通常是将其分解为更小的问题。从描述中我根本不清楚生成输出所需的算法。我有一个棋盘,它表示为列表列表。我想把棋盘分成四个部分,右上角和右下角,左上角和左下角,这是四个存储每个角的列表。我想要一个返回4个列表的函数。如果你想象不确定地选择前半部分或后半部分,它可以做得更简洁。So:topbottomxs=让l,r=在[l,r]中拆分长度为xs`div`2xs;leftRight=转置。地图上下;角落=左-右>=>上-下。如果真的有必要扔掉额外的结构,你可以在最后扔一张地图,但我怀疑保留它更有用。谢谢,这是一个很好的方法。我甚至没有意识到标准库中有转置函数!
*Main>let board = [[1,1,1,1], [0,0,0,0], [1 ,1, 0,0] , [0, 0, 1,1]]
*Main> allCorners board
[[1,1,0,0],[1,1,0,0],[0,0,1,1],[1,1,0,0]]
*Main> let board = [[1,1,1,1,1,1], [0,0,0,0,0,0], [1 ,1, 0,0,1,1] , [0, 0, 1,1,0,0], [1,1,1,1,1,1], [0,0,0,0,0,0]]
*Main>allCorners board
[[0,0,0,1,1,1,1,0,0],[1,1,1,0,0,0,0,1,1],[0,0,0,1,1,1,0,0,1],[1,1,1,0,0,0,1,1,0]]