HaskellWiki

Haskell | Wiki community | Recent changes
Random page | Special pages

 

Not logged in
Log in | Help

Algebraic data type

(Redirected from Algebraic datatype)

Categories: Language | Glossary

This is a type where we specify the shape of each of the elements.

Contents

1 Tree examples

Suppose we want to represent the following tree:

              5
             / \
            3   7
           / \
          1   4

We may actually use a variety of Haskell data declarations that will handle this.

1.1 Binary search tree

In this example, values are stored at each node, with smaller values to the left, greater to the right.

data Stree a = Tip | Node (Stree a) a (Stree a)

and then our example tree would be:

  etree = Node (Node (Node Tip 1 Tip) 3 (Node Tip 4 Tip)) 5 (Node Tip 7 Tip)

To maintain the order, such a tree structure is usually paired with a smart constructor.

1.2 Rose tree

Alternatatively, it may be represented in what appears to be a totally different stucture.

data Rose a = Rose a [Rose a]

In this case, the examlple tree would be:

retree = Rose 5 [Rose 3 [Rose 1 [], Rose 4[]], Rose 7 []]

The differences between the two are that the (empty) binary search tree Tip is not representable as a Rosetree, and a Rose tree can have arbitrary an dinternally varying branching factor (0,1,2, or more).

2 See also

Retrieved from "http://www.haskell.org/haskellwiki/Algebraic_data_type"

This page has been accessed 3,143 times. This page was last modified 13:09, 25 July 2008. Recent content is available under a simple permissive license.