【发布时间】:2010-02-25 16:27:03
【问题描述】:
我对 Haskell 很陌生,我正在尝试找出如何遍历 n 叉树。作为输出,我希望得到一个叶子值列表(因为分支没有值),所以对于 testtree 这将是:4,5
到目前为止我的定义是:
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
任何帮助将不胜感激,所以在此先感谢..!
【问题讨论】:
标签: haskell functional-programming tree