Haskell中的矩阵运算

时间:2012-05-25 20:29:17

标签: haskell matrix functional-programming

我有一个问题要展开矩阵。以下是程序输出的外观。我有点卡住了。

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

1 个答案:

答案 0 :(得分:0)

如果所有子列表都相同,则不需要transpose2,这与transpose中的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]