这是我的代码:
connected :: [(Integer,Integer)] -> Bool
connected [] = True
connected [(_,_)] = True
connected (a,b):(c,d):xs
| a > c = False
|otherwise = connected (c,d):xs
当我加载它时,它会显示 GHCi
error: parse error in pattern: connected
我哪里出错了?
最佳答案
您需要在两个位置的 cons 表达式周围添加括号:
connected :: [(Integer,Integer)] -> Bool
connected [] = True
connected [(_,_)] = True
connected ((a,b):(c,d):xs) -- (2)
| a > c = False
| otherwise = connected ((c,d):xs) -- (1)
函数应用程序比中缀运算符绑定(bind)更紧密,因此
connected (c,d) : xs
被解析为(connected (c,d)) : xs
.类似的事情也发生在模式表达式中。尽管您收到的无用错误消息相当不幸。
固执己见的旁注:我建议始终编写带有空格的中缀运算符(例如,a : b
而不是a:b
),因为我认为省略空格巧妙地暗示该运算符比实际绑定(bind)得更紧密。
关于Haskell: "parse error in pattern"在哪里,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46067091/