haskell中的Matrix Identity没有列表

时间:2016-04-18 18:39:40

标签: haskell

我想制作一个没有列表语法或列表函数的Identity矩阵,例如带有元组(x,x)的东西......我想打印它像

*> showMatrix (matrixIdentity 4)
1 0 0 0
0 1 0 0
0 0 1 0
0 0 0 1 

1 个答案:

答案 0 :(得分:1)

这是创建单一矩阵的技巧

import Data.List.Split(splitEvery)
identity n = splitEvery n $ take (n*n) $ concat $ replicate n (1:replicate n 0)

现在,要以该格式获得输出,您可以

putStr $ unlines $ map (unwords . map show) (identity 3)

打包这些

import Data.List.Split(splitEvery)
data IdentityMatrix = I Int
showMatrix :: IdentityMatrix -> IO ()
showMatrix (I n) = putStr $ unlines $ map (unwords . map show) identity
       where identity = splitEvery n $ take (n*n) $ concat $ replicate n (1:replicate n 0)


> showMatrix (I 4)
1 0 0 0
0 1 0 0
0 0 1 0
0 0 0 1