Yas*_*deh 0 haskell haskell-platform
我试图解决Haskell中的8皇后问题,而不使用任何高级功能,只有基本知识.我只走到这一步,但我得到一个我无法理解的错误.代码:
queens = [[x1,x2,x3,x4,x5,x6,x7,x8] | x1<-[1..8], x2<-[1..8],
x3<-[1..8], x4<-[1..8], x5<-[1..8],
x6<-[1..8], x7<-[1..8], x8<-[1..8],
safeH [x2,x3,x4,x5,x6,x7,x8] x1]
safeH xs e = if length xs == 1 then head xs
else e /= safeH (tail xs) (head xs)
Run Code Online (Sandbox Code Playgroud)
并且错误消息是:
y.hs:1:42:
No instance for (Num Bool) arising from the literal `1'
Possible fix: add an instance declaration for (Num Bool)
In the expression: 1
In the expression: [1 .. 8]
In a stmt of a list comprehension: x1 <- [1 .. 8]
[1 of 1] Compiling Main ( y.hs, interpreted )
Failed, modules loaded: none.
Run Code Online (Sandbox Code Playgroud)
罪魁祸首是
.........
safeH [x2,x3,x4,x5,x6,x7,x8] x1]
safeH xs e = if length xs == 1 then head xs
else e /= safeH (tail xs) (head xs)
Run Code Online (Sandbox Code Playgroud)
特别,
else e /= safeH (tail xs) (head xs)
Run Code Online (Sandbox Code Playgroud)
因为e == x1.所以一方面safeH返回Bool,在列表理解中用作测试.OTOH你比较它的结果x1.1除其他外,这是(x1<-[1..8]).即Num1.哪个也必须是Bool.因此错误.
1数字文字,例如1被解析为多态类型的值Num a => a.即它的具体类型必须属于Num类型类.由于具体类型也被确定为是Bool在这里,这意味着Bool必须属于Num类型的类,这个代码类型检查.因此instance for (Num Bool)寻求.