My Custom type is:
data Tree a = Leaf a | Node [Tree a] deriving (Show, Eq)
I need to write a function
foo :: Eq a => a -> Tree a -> [Tree a]
Example
foo 3 (Node [Leaf 1, Leaf 3, Node [Leaf 5, Leaf 3, Leaf 6], Leaf 4, Leaf 3, Leaf 44, Leaf 3])
-- this should print [Node [leaf 5, leaf 3, leaf 6], leaf 6, leaf 44] i.e - all elements that follow a "Leaf 3" in the Tree
My code is as follows (using pattern matching)
foo n (Leaf _) = []
foo n (Node (Node z):y:xs) = if length (Node z):y:xs < 2 then []
else (foo n (Node z)):(foo n y:xs)
foo n (Node (Leaf z):y:xs) = if length (Leaf z):y:xs < 2 then []
else if Leaf n == Leaf z then [y]:(foo n y:xs)
else (foo n y:xs)
However I get an error:
• Couldn't match expected type ‘Tree a’ with actual type ‘[Tree a]’
• In the pattern: Node (Node z) : y : xs
But the pattern Node (Node z) : y : xs
could represent the input
Node [Node [Leaf 4, Leaf 2], Leaf 6, Leaf 9, Leaf 1]
Am I wrong in saying that? It seems perfect to me.
Why then, is the pattern matching failing?
Node (Node z)
is evaluated first, because it is function application, but it can't evaluate, because the firstNode
is expecting a[Tree]
but receiving what appears to be aTree
. TryNode (Node z:y:xs)
. (Similarly parenthesize_:_:_
s in the sequel). – aplainzetakind(Leaf z):y:xs
surely has length >=2, so testing for that looks wrong. The testLeaf n == Leaf z
is weird, why notn == z
? More in general, usinglength
is often the wrong way: pattern matching already gives us information about the list length. – chi