Haskell 哈斯克尔:在哪里;模式“中的分析错误”;

Haskell 哈斯克尔:在哪里;模式“中的分析错误”;,haskell,pattern-matching,operator-precedence,parse-error,Haskell,Pattern Matching,Operator Precedence,Parse Error,这是我的代码: connected :: [(Integer,Integer)] -> Bool connected [] = True connected [(_,_)] = True connected (a,b):(c,d):xs | a > c = False |otherwise = connected (c,d):xs 当我加载它时,它显示为GHCi 错误:模式中的分析错误:已连接 我哪里出错了

这是我的代码:

connected :: [(Integer,Integer)] -> Bool
connected [] = True
connected [(_,_)] = True
connected (a,b):(c,d):xs
                 | a > c     = False
                 |otherwise = connected (c,d):xs
当我加载它时,它显示为GHCi

错误:模式中的分析错误:已连接


我哪里出错了?

您需要在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)
  • 函数应用程序绑定比中缀运算符更紧密,因此
    connected(c,d):xs
    被解析为
    (connected(c,d)):xs

  • 模式表达式中也会发生类似的情况。虽然你在那里得到的无用的错误信息是相当不幸的


  • 固执己见的旁注:我建议编写中缀运算符时始终使用空格(例如,
    a:b
    而不是
    a:b
    ),因为我认为省略空格微妙地意味着运算符绑定得比实际绑定得更紧。

    次要样式注释:
    foo | x=False |否则=something
    (IMO)更常见的书写形式是
    foo=notx&&something
    。在您的情况下,可以使用
    connected(…)=a