树的代数数据类型

时间:2013-01-15 18:52:11

标签: haskell tree algebraic-data-types

我正在尝试构建一个树,其子项在列表中表示。每个孩子本身可能都是子树等等。所以我这样走 -

data Children a = NoChildren | Cons a (Children a) deriving (Show, Read, Ord, Eq)
data Tree a = EmptyTree | Node a (Children a) deriving (Show, Read, Ord, Eq)

现在我尝试创建一个像这样的树

let subtree1 = Node 67 NoChildren
let subtree2 = Node 86 NoChildren
let tree1 = Node 83 (subtree1 `Cons` (subtree2 `Cons` NoChildren))

直到子树2才能正常工作。 tree1未创建。引发的错误是 -

<interactive>:96:15:
    No instance for (Num (Tree Integer))
      arising from the literal `83'
    Possible fix: add an instance declaration for (Num (Tree Integer))
    In the first argument of `Node', namely `83'
    In the expression: Node 81 (subtree1 `Cons` (subtree2 `Cons` NoChildren))
    In an equation for `tree1':
      tree1 = Node 81 (subtree1 `Cons` (subtree2 `Cons` NoChildren))

我根本不明白这个错误错误。为什么抱怨83是文字。 subtree1和subtree2也有文字,它们很好......

我通过以下方式解决了这个问题

data Tree a = EmptyTree | Node a [Tree a] deriving (Show, Read, Ord, Eq)

flatten [] = []
flatten x:xs = x ++ flatten xs

preorder EmptyTree = []
preorder (Node a []) = [a]
preorder (Node a children) = [a] ++ flatten (map preorder children)

0 个答案:

没有答案