【发布时间】:2019-03-01 15:29:22
【问题描述】:
假设我想用
在 Haskell 中建模一个树结构data Tree = Null | Node Tree Integer Tree deriving Show
我想测试每个条目是否小于 10。我想我会使用模式匹配并编写
isSmall :: Tree -> Bool
isSmall _
| Null = True
| (Node a b c) = if b >= 10
then False
else isSmall a && isSmall c
但是它给出了关于a、b 和c 超出范围的错误。我原以为将它们放在警卫中基本上会将它们放在范围内。这不是你应该在 Haskell 中进行模式匹配的方式吗?我环顾四周寻找可以指导我的示例,但我没有在使用由其他几种数据结构组成的数据结构的守卫中找到任何模式匹配示例。
错误:
test.hs:24:6: Not in scope: data constructor ‘Node’
test.hs:24:11: Not in scope: ‘a’
test.hs:24:13: Not in scope: ‘b’
test.hs:24:15: Not in scope: ‘c’
test.hs:24:27: Not in scope: ‘b’
test.hs:26:38: Not in scope: ‘a’
test.hs:26:57: Not in scope: ‘c’
【问题讨论】:
-
你能发布确切的错误吗?
-
@DavOS 编辑了错误。
-
你为什么要把图案放在守卫里?
-
"这不是你应该在 Haskell 中进行模式匹配的方式吗?" 不。守卫是布尔表达式,而不是模式。
-
if A then False else B最好写成not A && B。
标签: haskell pattern-matching guard-clause