【问题标题】:Haskell parsing error on ‘|’ symbol with WinGHCi使用 WinGHCi 的“|”符号上的 Haskell 解析错误
【发布时间】:2017-10-22 18:10:44
【问题描述】:

我是 Haskell 的新手,遇到了这个臭名昭著的错误。

我已经查阅了这些链接: Haskell: parse error on input `|'Haskell parse error on input '|'Haskell - parse error on input `|'Why complains Haskell parse error on input `|' in this Function?Haskell parse error on input `|'

真正让我吃惊的是,我完全复制了我大学老师在课堂上给我们的代码:

data TreeInt = Leaf Int
             | Node TreeInt Int TreeInt
foo :: TreeInt -> Int
foo arg =
 case arg of
  | Leaf x = x
  | Node tLeft x tRight = x

我知道问题在 foo arg 下面,因为下面的代码可以编译:

data TreeInt = Leaf Int 
             | Node TreeInt Int TreeInt
foo :: TreeInt -> Int
foo arg = undefined

确切的错误是:hw.hs:6:4: error: parse error on input ‘|’ 这让我相信它在第 6 行 (| Leaf)。

我尝试过的:

  • 使用模式匹配转换代码(出现另一个错误)
  • 将 case 与 foo arg 放在同一行
  • 添加更多/更少的空格
  • 添加“let”,因为某些版本的 GHC 没有它会出现问题(没有变化)

【问题讨论】:

    标签: haskell


    【解决方案1】:

    代替这个(#1):

    case arg of
      | Leaf x = x
      | Node tLeft x tRight = x
    

    你想要这个(#2):

    case arg of
      Leaf x -> x
      Node tLeft x tRight -> x
    

    #1 的风格用于其他 ML 家族语言,例如 OCaml:

    match arg with
      | Leaf x -> x
      | Node (tLeft, x, tRight) -> x
    

    但 Haskell 使用“布局规则”将 #2 脱糖为以下内容:

    case arg of {
      Leaf x -> x;
      Node tLeft x tRight -> x;
    }
    

    (事实上,如果你愿意,你可以明确地写出来。)

    还要注意,->case 表达式一起使用,= 与定义一起使用:

    foo arg =
      case arg of
        Leaf x -> x
        Node tLeft x tRight -> x
    
    foo' (Leaf x) = x
    foo' (Node tLeft x tRight) = x
    

    即使模式上有保护表达式也是如此——竖线 (|) 的实际用途是:

    foo arg =
      case arg of
        Leaf x
          | x < 0 -> 0
          | otherwise -> x
        Node tLeft x tRight
          | x < 0 -> 0
          | otherwise -> x
    
    foo' (Leaf x)
      | x < 0 = 0
      | otherwise = x
    foo' (Node tLeft x tRight)
      | x < 0 = 0
      | otherwise = x
    

    【讨论】:

      猜你喜欢
      • 2016-10-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-19
      • 2011-09-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多