如何在 haskell 中使用合理的缩进初始化矩阵

How can I initialize matrices with sensible indentation in haskell

我想在 haskell 中得到一个用硬编码值填充的矩阵。然而,由于 haskell 中的缩进规则,我设法做到这一点的唯一方法是将整个矩阵写在难以阅读的一行上。

matrix = [                          
   [1,0,0],
   [0,2,0],
   [0,0,3]
] --parse error (possibly incorrect indentation or mismatched brackets)

matrix = [ [1,0,0], [0,1,0], [0,0,1] ] --OK

推荐的方法是什么?

haskell 社区决定我们喜欢缩进的方式是:

matrix = [ [1, 0, 0 ]
         , [0, 2, 0 ]
         , [0 ,0 ,3 ]
         ]

matrix = [ [1, 0, 0 ]
         , [0, 2, 0 ]
         , [0 ,0 ,3 ] ]

前导逗号是目前最主要的风格:)

你也可以把矩阵降下来

matrix =
  [ [1, 0, 0 ]
  , [0, 2, 0 ]
  , [0 ,0, 3 ] ]

matrix =
  [ [1, 0, 0 ]
  , [0, 2, 0 ]
  , [0 ,0, 3 ]
  ]

您的示例的问题在于,只有缩进 "past the m" 的内容才被视为 "still a part of the declaration of matrix"。例如:

matrix = blah
  bloh
bluh

bluhm 处于同一水平,因此 haskell 看到 bluh 并且去 "welp, this is a new declaration! we're done with matrix!"

诚然,编译器错误可能会更清楚一些:)