我對Haskell來說很新,而且我正試着研究如何遍歷n元樹。作爲輸出我希望得到葉值的列表(如樹枝沒有任何價值),所以testtree這將是:4,5Haskell n元樹遍歷
我的定義到目前爲止是:
data Tree a = Leaf a | Branch [Tree a] deriving (Show)
travTree :: Tree a -> [a]
travTree (Leaf x) = [x]
travTree (Branch (x:xs)) = travTree x : travTree xs
testtree = Branch [(Leaf "4"), (Leaf "5")]
但它給出了錯誤:
Couldn't match expected type `Tree a'
against inferred type `[Tree a]'
In the first argument of `travTree', namely `xs'
In the second argument of `(:)', namely `travTree xs'
In the expression: travTree x : travTree xs
我假設這是由於xs是一個樹列表和期望單數樹。有沒有辦法做到這一點?我一直試圖在地圖功能,沿着線:
travTree (Branch (x:xs)) = travTree x : map travTree xs
但隨後抱怨的:
Occurs check: cannot construct the infinite type: a = [a]
When generalising the type(s) for `travTree'
我也試圖改變函數簽名:
travTree :: Tree a -> [b]
這給出了錯誤:
Couldn't match expected type `a' against inferred type `[b]'
`a' is a rigid type variable bound by
the type signature for `travTree' at Main.hs:149:36
In the first argument of `(:)', namely `travTree x'
In the expression: travTree x : map travTree xs
In the definition of `travTree':
travTree (Branch (x : xs)) = travTree x : map travTree xs
任何幫助將不勝感激,所以在此先感謝..!
你的第一個答案與清單理解是非常好的......但很高興看到你同意我的回答呢! – Nefrubyr 2010-02-25 16:46:47
你也可以使用concatMap;) – hiena 2010-02-25 16:47:01
我喜歡這個解決方案,因爲它將它分解了一下。我同意,它比concatMap函數更清晰。我也很喜歡列表理解(雖然最初理解起來有點複雜),所以再次感謝! :-) – Matt 2010-02-25 18:16:18