首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >用WinGHCi对符号进行Haskell解析错误

用WinGHCi对符号进行Haskell解析错误
EN

Stack Overflow用户
提问于 2017-05-23 00:04:19
回答 1查看 320关注 0票数 2

我是新来的哈斯克尔,并得到这个臭名昭著的错误。

我已经查阅了以下链接: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 `|'

真正令我惊讶的是,我准确地抄袭了,也就是我的大学老师在课堂上给我们的代码:

代码语言:javascript
运行
复制
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下面,因为下面的代码编译:

代码语言:javascript
运行
复制
data TreeInt = Leaf Int 
             | Node TreeInt Int TreeInt
foo :: TreeInt -> Int
foo arg = undefined

准确的错误是:hw.hs:6:4: error: parse error on input ‘|’,这让我相信它在第6行({##**$$}})。

我试过的是:

  • 使用模式匹配转换代码(获得另一个错误)
  • 把箱子和foo arg放在同一条线上
  • 增加更多/更少的空间
  • 添加"let“,因为一些版本的GHC没有问题(没有更改)
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-05-23 00:08:01

而不是这个(#1):

代码语言:javascript
运行
复制
case arg of
  | Leaf x = x
  | Node tLeft x tRight = x

你想要这个(#2):

代码语言:javascript
运行
复制
case arg of
  Leaf x -> x
  Node tLeft x tRight -> x

#1的样式在其他ML-家庭语言中使用,例如OCaml:

代码语言:javascript
运行
复制
match arg with
  | Leaf x -> x
  | Node (tLeft, x, tRight) -> x

但是Haskell使用“布局规则”将desugar #2转换为以下内容:

代码语言:javascript
运行
复制
case arg of {
  Leaf x -> x;
  Node tLeft x tRight -> x;
}

(事实上,如果您愿意,可以显式地编写它。)

还请注意,->用于case表达式,=用于定义:

代码语言:javascript
运行
复制
foo arg =
  case arg of
    Leaf x -> x
    Node tLeft x tRight -> x

foo' (Leaf x) = x
foo' (Node tLeft x tRight) = x

即使在模式上有一个保护表达式,这也是正确的--垂直条形图(|)实际上用于:

代码语言:javascript
运行
复制
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
票数 7
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/44123811

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档