I am currently working on Problem 62
I have tried the following code to solve it:
data Tree a = Empty | Branch a (Tree a) (Tree a)
deriving (Show, Eq)
internals :: Tree a -> [a]
internals (Branch a Empty Empty) = []
internals (Branch a b c) = [a]++(internals b)++(internals c)
internals (Branch a b Empty) = [a]++(internals b)
internals (Branch a Empty c) = [a]++(internals c)
Which basically says:
- If both the children are empty don’t include that list element in the list of internals.
- If both children are non-empty, that node (
a) is an internal include it, and keep checking to see any ofa‘s children are also internal. - If one of the children is non-empty, that node is internal, and recursively keep checking if the child is also an internal node.
In GHCi I have ran the following:
> let tree4 = Branch 1 (Branch 2 Empty (Branch 4 Empty Empty)) (Branch 2 Empty Empty)
> internals tree4
and get the following runtime error:
[1,2*** Exception: Untitled.hs:(6,1)-(12,49): Non-exhaustive patterns in function internals
I don’t understand why this thing is non-exhaustive, I thought it would go to branch 1, notice it’s children are non-empty, then go down both branch 2s and find out one branch is empty, one is not, stop at the one that is, and keep going down the one that isn’t, until branch “4”, and end it there. It sort of does, I do get 1, 2 in the list, but why is it not exhaustive?
Thanks in advanced.
Thank you for the help Tikhon changed my function to this:
data Tree a = Empty | Branch a (Tree a) (Tree a)
deriving (Show, Eq)
internals :: Tree a -> [a]
internals (Branch a Empty Empty) = []
internals (Branch a b Empty) = [a]++(internals b)
internals (Branch a Empty c) = [a]++(internals c)
internals (Branch a b c) = [a]++(internals b)++(internals c)
The order of patterns matters. Since
Branch a b cmatches everything that isn’t justEmpty, including something likeBranch a b Empty, your third and fourth cases never get hit.This should fix it: