2017-09-06 120 views
3

的 “图案解析错误” 这是我的代码:哈斯克尔:哪里是

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

哪儿了我犯了一个错误?

+0

小调注意:'foo | x = False |否则= something'是(IMO)更常被写为'foo = not x && something'。在你的情况下,你可以使用'connected(...)= a <= c && connected(...)'。 – chi

回答

7

您需要在两个地方周围添加你的缺点表达式括号:

connected :: [(Integer,Integer)] -> Bool 
connected [] = True 
connected [(_,_)] = True 
connected ((a,b):(c,d):xs)       -- (2) 
       | a > c  = False 
       | otherwise = connected ((c,d):xs) -- (1) 
  1. 功能应用结合更加紧密地比中缀运算符,所以connected (c,d) : xs被解析为(connected (c,d)) : xs

  2. 类似的事情发生在模式表达式中。虽然你得到的无用的错误信息是相当不幸的。

固执己见侧面说明:我建议总是写缀运营商与周围空间(例如,a : b代替a:b),因为我觉得忽略空白巧妙地暗示了运营商结合更加紧密比它确实做到了。