【问题标题】:Haskell: where is the "parse error in pattern" [duplicate]Haskell:“模式中的解析错误”在哪里 [重复]
【发布时间】:2018-02-14 11:09:32
【问题描述】:

这是我的代码:

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

我在哪里做错了?

【问题讨论】:

  • 次要风格注释:foo | x = False | otherwise = something 是(IMO)更常见的写作foo = not x && something。在您的情况下,您可以使用connected (...) = a <= c && connected (...)。

标签: haskell pattern-matching operator-precedence parse-error


【解决方案1】:

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

  2. 在模式表达式中也会发生类似的事情。尽管您收到的无用错误消息很不幸。

有意见的附注:我建议始终编写带有空格的中缀运算符(例如,a : b 而不是 a:b),因为我认为省略空格会巧妙地暗示运算符的绑定比实际更紧密。

【讨论】:

    猜你喜欢
    • 2012-09-28
    • 2012-01-23
    • 2013-01-29
    • 1970-01-01
    • 2015-03-14
    • 2012-12-24
    • 2017-10-29
    • 1970-01-01
    • 2019-05-03
    相关资源
    最近更新 更多