2017-10-10 154 views
1

我是新來的Haskell和一直在試圖建立一個荏苒功能,與具有以下數據結構樹的工作原理:哈斯克爾:問題荏苒樹

data Tree a = Leaf | Node a (Tree a) (Tree a) deriving Show 

到目前爲止,我有這樣的:

treezip :: (Tree a) -> (Tree b) -> (Tree(a,b)) 
treezip (Node a leftSubtreea rightSubtreea) (Node b leftSubtreeb rightSubtreeb) = 
let l = treezip leftSubtreea leftSubtreeb 
    r = treezip rightSubtreea rightSubtreeb 
in Node a l r 

但是,無論何時我嘗試將模塊加載到GHCi中,我都會收到錯誤,指向代碼的最後一行,並且特別注意變量a

我一直在試圖弄清楚爲什麼這不起作用。任何幫助,將不勝感激

+1

提示:節點在壓縮後應該存儲的值應該是多少? –

+0

「節點」應該在壓縮後存儲「內部」值。 –

+1

@ J.Doe「Int」從哪裏來? 'treezip'需要存儲任意數據的兩棵樹,並生成一個包含*元組數據*的樹。如果我有一個Tree Char值和一個Tree Bool值,我必須產生一個Tree(Char,Bool)值。那麼,'treezip(Node'c'Leaf Leaf)(Node'True'Leaf Leaf)'應該返回什麼? – chepner

回答

4

不要針對編譯器,讓它幫助你!

向右像這樣的功能,這是最好的,只有一個「外殼定義」開始了:

treeZip (Node a lSa rSa) (Node b lSb rSb) = Node _ _ _ 

編譯器會回來這個:

• Found hole: _ :: (a, b) 
    Where: ‘a’ is a rigid type variable ...(_bla, bla_) 
     ‘b’ is a rigid type variable .... 
• In the first argument of ‘Node’, namely ‘_’ 
    In the expression: Node _ _ _ 
    In an equation for ‘treeZip’: 
     treeZip (Node a lSa rSa) (Node b lSb rSb) = Node _ _ _ 
• Relevant bindings include 
    rSb :: Tree b (bound at /tmp/wtmpf-file20584.hs:4:38) 
    lSb :: Tree b (bound at /tmp/wtmpf-file20584.hs:4:34) 
    b :: b (bound at /tmp/wtmpf-file20584.hs:4:32) 
    rSa :: Tree a (bound at /tmp/wtmpf-file20584.hs:4:21) 
    lSa :: Tree a (bound at /tmp/wtmpf-file20584.hs:4:17) 
    a :: a (bound at /tmp/wtmpf-file20584.hs:4:15) 

所以,告訴你第一個_打孔應該填充(a,b)類型的東西。我們有這種類型的東西嗎?那麼,我們可以輕鬆地構建它,即將ab並將它們放在一個元組中!

treezip (Node a lSa rSa) (Node b lSb rSb) = Node (a,b) _ _ 

...給

• Found hole: _ :: Tree (a, b) 
    Where: ‘a’ is a rigid type variable bound by... 

是啊,你已經解決了一個 - 它應該是子樹的拉鍊。

treeZip (Node a lSa rSa) (Node b lSb rSb) 
    = Node (a,b) (treeZip lSa lSb) (treeZip rSa rSb)