I’m trying to build a tree where its children are represented in a list. Each of the children may themselves be subtrees etc. So I go this way —
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)
now i try to create a tree like this
let subtree1 = Node 67 NoChildren
let subtree2 = Node 86 NoChildren
let tree1 = Node 83 (subtree1 `Cons` (subtree2 `Cons` NoChildren))
it works fine till subtree2. tree1 is not created. The error thrown is this –
<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))
I don’t understand this error error at all. Why is it complaining that 83 is a literal. subtree1 and subtree2 had literals too and they were fine…
I solved the problem by doing the following
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)
means your
Children ais isomorphic to[a], and hence youris isomorphic to
which is again isomorphic to
[a].What you want is that the children themselves are
Trees, so you should useor plain
The error is because
subtree1has typeTree afor someabelonging toNum(ditto forsubtree2). Then when you writethe inferred type of
tree1isTree (Tree a)(for someabelonging toNum), and henceBut there’s no
Numinstance forTrees.