我对Haskell非常陌生,我试图围绕语法(以及习惯于声明性语言)。我已经创建了一个树数据类型,我希望能够使用==运算符来比较它们。这就是我所拥有的:
data Tree =
Leaf
| Twig
| Branch Tree Tree Tree
deriving Show;
instance Eq Tree where
Leaf == Leaf = True;
(Branch a b c) == (Branch a1 b1 c1) = a==a1 && b==b1 && c==c1;
这在输入Leaf == Leaf
或Branch Leaf Leaf Leaf == Branch Leaf Leaf Leaf
时似乎有效,但在我添加Twig == Twig = True;
时它会一直给我一个错误。此外,无法比较Leaf == Branch Leaf Leaf Leaf
。我尝试使用_==_ = False;
,但这也给了我一个错误。我迷了,任何帮助都会非常感激!
编辑: 仍然有错误,特别是:
[1 of 1] Compiling Main ( Tree.hs, interpreted )
Tree.hs:15:5: parse error on input ‘_’
Failed, modules loaded: none.
Prelude> :r
[1 of 1] Compiling Main ( Tree.hs, interpreted )
Tree.hs:15:3: parse error on input ‘Twig’
Failed, modules loaded: none.
第一个是在我拿出有问题的Twig ==后,留下_ == _。第二个是留下两个。
答案 0 :(得分:6)
您的代码适用于我所添加的内容,您说错误,特别是
instance Eq Tree where
Leaf == Leaf = True;
(Branch a b c) == (Branch a1 b1 c1) = a==a1 && b==b1 && c==c1;
Twig == Twig = True;
_ == _ = False;
(顺便说一下,行末尾的;
是多余的。)
我怀疑你可能有缩进错误。你在混合标签和空格吗?
此外,所有实例声明都等同于将deriving
子句更改为
deriving (Show,Eq)
因为这正是默认派生Eq
实例的工作原理。