我正在尝试构建一棵树,其子项在列表中表示。每个孩子自己都可能是子树等。所以我走这条路——
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))
它工作正常,直到 subtree2。未创建 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)