Your tree type:
data Tree a b = Leaf a | Branch (b,Tree a b) (b,Tree a b)
A Tree a b
is either:
- a
Leaf
containing ana
value; or - a
Branch
containing two(b, Tree a b)
pairs.
The patterns you write must follow that structure. You must match first Leaf
or Branch
and then whatever is inside them. So your depth
should look like this:
depth :: Tree a b -> Int -- Always write signatures for your functions.
depth (Leaf x) = 1 -- There are no pairs anywhere in a Leaf.
depth (Branch (l1, t1) (l2, t2)) = 1 + max (depth t1) (depth t2)
The above can be made a little cleaner by noticing that, as we are not actually using the b
"labels" and a
"values", we can just ignore them. We do that with the _
pattern:
depth :: Tree a b -> Int
depth (Leaf _) = 1
depth (Branch (_, t1) (_, t2)) = 1 + max (depth t1) (depth t2)