I\'m going through the problems in the Haskell O\'Reilly book. The problem I am working on is
Using the binary tree type that we defined earlier in this chapter
Change
height (Tree node left right)
to
height (Node node left right)
That means the pattern matching works on the constructors of the algebraic data type (ADT). Tree
is not a constructor, it is the name of the ADT.
Btw, you have to comment out your function signature declaration to compile the code because it contains an error.
You can then check the inferred type via
:t height
in ghci or hugs.
Your code is wrong, on several levels. It looks like you misunderstood algebraic data types.
Tree
is always a Tree
of a specific type - which you called a
in its declaration, and which may be any type (since you didn't constraint it). So heigth
has to take a Tree
of some type - a Tree SomeType
, too. You can and should use the most generic type for SomeType
, i.e. a type variable like a
.Node a (Tree a) (Tree a)
or Empty
- to match against, not against the type as a whole. So height (Node ...)
would match a Node
, height (Empty)
would match a Empty
, and height (Tree ...)
would try to match a constructor named Tree
, but there is none. That's the error message you recieve.==
) with a Constructor. It would actually work if you wrote deriving (Show, Eq)
. But you should use pattern matching to determine if you reached an Empty
Node
, not Empty
- you should add a clause for Empty
.height
- which can, in turn, only return 0 or the max of their childrens' height
, etc ad infinitum. You have to increment the result at each level ;)You pattern-match against constructors, i.e. the cases, of your Tree
ADT. Tree
is just what sums them all up.
It's much more straightforward like this, and, most of all, correct:
height Empty = 0
height (Node _ l r) = 1 + max (height l) (height r)