next up previous
Next: Polymorphic Functions Up: The Frightened Freshers Guide Previous: More fun (sic!) with

Trees

No, I am not making it up. This is a section about trees. A Tree structured datatype is great for...um...well actually I do not know of any examples it is good for other than something like a family tree, so here it goes.

Defining a Tree of Integers is done as below.


\begin{lstlisting}
-- Definition for the TreeInt datatype
data TreeInt = Leaf \v...
...ype
Node (Node (Node Leaf 1959 Leaf) 1986 (Node Leaf 1953 Leaf)
\end{lstlisting}

Once again you can see that this datatype uses recursion in its definition. The example of the TreeNode datatype represented graphically would have 1986 at the top with two nodes coming off it (1959 and 1953) which both would have leaves coming off them. Not too clear, but clearer when you draw it out for yourself!

A nice example of something neat you can do with Trees is finding its depth.


\begin{lstlisting}
- Definition of the depth function
- Uses the TreeInt datat...
...h Leaf = 0
depth (Node t1 n t2) = 1 + max (depth t1) (depth t2)
\end{lstlisting}

You can also do other funky things like finding the sum of all the elements in a tree using a similar layout.


\begin{lstlisting}
sumTree :: TreeInt -> Int
sumTree Leaf = 0
sumTree (Node t1 n t2) =
n + (sumTree t1) + (sumTree t2)
\end{lstlisting}

Once again, this is another function that uses recursion to achieve its goal! sumTree calls sumTree and so on until sumTree hits a Leaf when it returns 0 instead.

Lists can be a real pain to debug and hugs, as was noted earlier, does not allow you as a programmer to step through and see where things are going wrong.


next up previous
Next: Polymorphic Functions Up: The Frightened Freshers Guide Previous: More fun (sic!) with
Tom Carlson 2006-04-11