gpt4 book ai didi

Haskell 使用 WinGHCi 解析 ‘|’ 符号时出错

转载 作者:行者123 更新时间:2023-12-02 10:48:06 26 4
gpt4 key购买 nike

我是 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 ‘|’这让我相信它在第六行(|叶)。

我尝试过:

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

最佳答案

而不是这个(#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

关于Haskell 使用 WinGHCi 解析 ‘|’ 符号时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44123811/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com