Haskell解析错误'|' 符号与WinGHCi

Mau*_*ude 2 haskell

我是Haskell的新手并且得到了这个臭名昭着的错误.

我已经查阅了这些链接: Haskell:输入"|"时解析错误 输入'|'上的Haskell解析错误 Haskell - 输入"|"时的解析错误 为什么在输入"|"时抱怨Haskell解析错误 在这个功能? 输入"|"时Haskell解析错误

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

data TreeInt = Leaf Int
             | Node TreeInt Int TreeInt
foo :: TreeInt -> Int
foo arg =
 case arg of
  | Leaf x = x
  | Node tLeft x tRight = x
Run Code Online (Sandbox Code Playgroud)

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

data TreeInt = Leaf Int 
             | Node TreeInt Int TreeInt
foo :: TreeInt -> Int
foo arg = undefined
Run Code Online (Sandbox Code Playgroud)

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

我尝试过的:

  • 使用模式匹配转换代码(得到另一个错误)
  • 将案例放在与foo arg相同的行上
  • 添加更多/更少的空间
  • 添加"let",因为某些版本的GHC在没有它的情况下会出现问题(没有变化)

Jon*_*rdy 5

而不是这个(#1):

case arg of
  | Leaf x = x
  | Node tLeft x tRight = x
Run Code Online (Sandbox Code Playgroud)

你想要这个(#2):

case arg of
  Leaf x -> x
  Node tLeft x tRight -> x
Run Code Online (Sandbox Code Playgroud)

#1的样式用于其他ML系列语言,例如OCaml:

match arg with
  | Leaf x -> x
  | Node (tLeft, x, tRight) -> x
Run Code Online (Sandbox Code Playgroud)

但是Haskell使用"布局规则"来解释#2以下内容:

case arg of {
  Leaf x -> x;
  Node tLeft x tRight -> x;
}
Run Code Online (Sandbox Code Playgroud)

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

另请注意,您使用->case表情和=与定义:

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

foo' (Leaf x) = x
foo' (Node tLeft x tRight) = x
Run Code Online (Sandbox Code Playgroud)

即使在模式上有一个保护表达式也是如此 - 这是垂直条(|)实际用于:

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
Run Code Online (Sandbox Code Playgroud)