我做了一个类似于这个错误的线程,其中我解释了我的程序。这里the link
我在我的项目中前进,我还有另外一个问题。我做了另一个帖子,但如果我只需要编辑第一个,请告诉我。
我想要扭转我的矩阵。例如[[B,B,N],[N,B,B]]将变为[[B,N],[B,B],[N,B]]。这是我的代码:
transpose :: Grille -> Grille
transpose [] = []
transpose g
| head(g) == [] = []
| otherwise = [premierElem(g)] ++ transpose(supp g)
supp :: Grille -> Grille
supp [] = []
supp (g:xg) = [tail(g)] ++ supp(xg)
premierElem :: Grille -> [Case]
premierElem [] = []
premierElem (x:xg) = [head(x)] ++ premierElem(xg)
我得到了完全相同的错误,我尝试了第一个,但那不是。
编辑:确切的错误
*Main> transpose g0
[[B,B,N,B,N,B],[B,B,B,B,N,B],[B,N,N,B,N,B],[B,B,N,N,B,N],[B,N,N,N,B,N],[B,B,N,B,B,B],[N,B,N,N,B,N],[*** Exception: Prelude.head: empty list
答案 0 :(得分:3)
问题是您的transpose
函数的终止条件已损坏。怎么知道什么时候停止?尝试手动完成最后一步......
通常,您的案例transpose [] = []
将永远不会发生,因为您的supp
函数永远不会更改其参数中的列表数。格式良好的矩阵最终将为[[],[],[],...]
,与[]
不匹配。唯一能阻止它的是你收到的错误。
因此,您需要检查嵌套(行?)向量的剩余长度,如果为零则停止。有很多方法可以解决这个问题;如果不是作弊,你可以查看Prelude文档中transpose
的实现。
此外,请重新评论上述内容:如果您希望您的输入在某种程度上形成良好形式,则应通过抱怨格式错误的输入来覆盖任何排除的案例,例如报告error
。< / p>
答案 1 :(得分:2)
Fixing Your Code
You should avoid using partial functions, such as tail and head, and instead make your own functions do (more) pattern matching. For example:
premierElem g = [head(head(g))] ++ premierElem(tail(g))
Yuck! If you want the first element of the first list in g
then match on the pattern:
premierElem ((a:_):rest) = [a] ++ premierElem rest
This in and of itself is insufficient, you'll want to handle the case where the first list of the Grille
is an empty list and at least give a useful error message if you can't use a reasonable default value:
premeirElem ([]:rest) = premeirElem rest
Making Better Code
Eventually you will become more comfortable in the language and learn to express what you want using higher level operations, which often means you'll be able to reuse functions already provided in base
or other libraries. In this case:
premeirElem :: [[a]] -> [a]
premeirElem = concatMap (take 1)
Which assumes you are OK with silently ignoring []
. If that isn't your intent then other similarly concise solutions can work well, but we'd need clarity on the goal.