我是一个新手Haskell程序员,正在尝试遍历一颗N叉树。输出结果应该是一个叶子值的列表(因为分支没有值),所以对于测试树来说,输出应该是: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是一组树,而它期望的是单个树。有没有办法解决这个问题?我一直在尝试使用map函数,大致如下:
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
任何帮助都将不胜感激,提前表示感谢..!