2014-11-05 27 views
1

我对Haskell非常陌生,我试图围绕语法(以及习惯声明性语言)进行思考。我创建了一个树型数据类型,我希望能够使用==运算符来比较它们。下面是我有: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 == LeafBranch 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. 

第一是我带出来的问题枝条==后,留下_ == _。二是无论是在离开。

+4

如果您发布了触发错误的确切代码,那么您可能会解释发生了什么问题。 – 2014-11-05 01:37:09

回答

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; 

(BTW的;在线路末端是多余的。)

我怀疑你可能有缩进错误。你在混合制表符和空格吗?

而且,所有实例声明的仅仅是相当于改变你的deriving子句

deriving (Show,Eq) 

因为这恰恰是如何默认衍生Eq实例工作。

+1

Haskell wikibook有一个关于缩进和布局规则的好的部分(http://en.wikibooks.org/wiki/Haskell/Indentation),提问者可能会觉得有用。特别是,它转换为“一维”分号格式。 – 2014-11-05 01:46:46