我对Haskell很新,我正在努力研究如何遍历一棵n-ary树.作为输出,我希望获得Leaf值列表(因为分支没有值),因此对于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")]
Run Code Online (Sandbox Code Playgroud)
但它给出了错误:
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
Run Code Online (Sandbox Code Playgroud)
我假设这是因为xs是一个树列表,它期待一棵奇异的树.有没有办法做到这一点?我一直在尝试地图功能,顺序如下:
travTree …Run Code Online (Sandbox Code Playgroud)