2

我在展开矩阵时遇到问题。这是程序的输出应该是这样的。我有点卡住了。

unfoldMatrix :: [ [a] ] -> [a]
Main> unfoldMatrix [[1, 2, 3],
                [4, 5, 6],
                [7, 8, 9],
                [10, 11, 12]]
[1,4,7,10,11,12,9,6,3,2,5,8]

我的代码有效,但它的输出是这种格式

[[1,4,7],[8,9],[6,3],[2],[5],[]]

任何想法如何更改代码以按需要工作?

transpose2:: [[a]]->[[a]]
transpose2 ([]:_) = []
transpose2 x = (map head x) : transpose2 (map tail x)


unfoldMatrix:: [[a]]->[[a]]
unfoldMatrix ([]:_) = []
unfoldMatrix x =(map head x):unfoldMatrix(tail2(x))

rotate90 :: [ [ a ] ] -> [ [ a ] ]
rotate90 = (map reverse).transpose2

tail2:: [[a]]->[[a]]
tail2 = (tail).rotate90
4

1 回答 1

0

您不需要transpose2,如果所有子列表都一样长,则与transposefrom相同Data.List。所以你的展开只是

Prelude Data.List> let unfold xxs@((_:_):_) = map head xxs ++ unfold (map reverse . transpose $ map tail xxs); unfold _ = []
Prelude Data.List> unfold [[1,2,3],[4,5,6],[7,8,9]]
[1,4,7,8,9,6,3,2,5]
Prelude Data.List> unfold [[1,2,3],[4,5,6],[7,8,9],[10,11,12]]
[1,4,7,10,11,12,9,6,3,2,5,8]
于 2012-05-25T20:56:23.323 回答