Trees

Lists are a very useful data structure, but not ideal for everything. For many applications, using trees will lead to asymptotically faster programs.

ML allows us to define new data structures including trees with a datatype declaration.

Example: binary trees with values at the internal nodes.

code45

This recursive declaration has two effects:

tex2html_wrap_inline100 It declares a brand-new type called intbtree.

tex2html_wrap_inline100 It declares two data constructors for that type.

These constructors can be used (like functions) to construct values of the datatype and can be used in patterns to analyze values.

Operations on trees

Suppose using ordered intbtree to represent sets.

code55

code57

Equivalent C code

code60

(Assume NULL pointer corresponds to LEAF.)

code64

Polymorphic trees

Can define a binary tree datatype that carries values of any type:

code67

Here bintree is really a type constructor, rather than a type, because it can be applied to arbitrary types 'a to construct new types 'a bintree.

As expected, we can define polymorphic functions over such types.

code73

Datatypes in General

The tree definitions we've seen are just a special case of a very general mechanism for defining new type (constructors).

In general, a datatype declaration may include:

tex2html_wrap_inline100 any number (>0) of data constructors, each with any number ( tex2html_wrap_inline108 ) of arguments;

tex2html_wrap_inline100 any number ( tex2html_wrap_inline108 ) of type variables;

tex2html_wrap_inline100 any number (> 0) of mutually-recursive type constructors.

Many familiar types (some of them built-in) are really just special cases of datatypes.

tex2html_wrap_inline100 Lists. Built-in lists behave just as though they were defined like this:

code77

tex2html_wrap_inline100 Discriminated union types in general.

tex2html_wrap_inline100 Booleans. Built-in booleans act just like this:

code79

tex2html_wrap_inline100 Enumerated types in general:

code81

tex2html_wrap_inline100 Option type.

code83



Andrew P. Tolmach
Tue May 6 18:23:22 PDT 1997