2014-11-05 29 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