Haskell - 使用函数创建列表

时间:2014-11-17 18:48:53

标签: haskell

我想做标题所说的,但它让我显示错误。我把我的代码放在下面。

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

treeToList :: Tree a -> [a]
treeToList (Leaf x) = [x]
treeToList (Branch a b) = (treeToList a):(treeToList b)

它会显示如下:

treeToList分支(分支(叶2)(叶3))(叶4)

[2,3,4]

1 个答案:

答案 0 :(得分:2)

在第一个模式匹配中,您将获得类型列表的值。现在,您只需在模式匹配Branch构造函数时将它们连接起来。

treeToList :: Tree a -> [a]
treeToList (Leaf x) = [x]
treeToList (Branch a b) = (treeToList a) ++ (treeToList b)

ghci中的演示:

*Main> treeToList (Branch (Branch (Leaf 2) (Leaf 3)) (Leaf 4))
[2,3,4]