假设我想在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
超出了范围。我本以为在 guard 中将它们放入作用域基本上就可以了。这不是 Haskell 中模式匹配的正确用法吗?我查看了一些可供参考的示例,但没有发现使用由几个其他数据结构组成的数据结构进行 guard 中的模式匹配的例子。错误信息:
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’
if A then False else B
更好地写作not A && B
。 - melpomene