Tagged Union - Examples

Examples

Say we wanted to build a binary tree of integers. In ML, we would do this by creating a datatype like this:

datatype tree = Leaf | Node of (int * tree * tree)

This is a tagged union with two cases: one, the leaf, is used to terminate a path of the tree, and functions much like a null value would in imperative languages. The other branch holds a node, which contains an integer and a left and right subtree. Leaf and Node are the constructors, which enable us to actually produce a particular tree, such as:

Node(5, Node(1,Leaf,Leaf), Node(3, Leaf, Node(4, Leaf, Leaf)))

which corresponds to this tree:

Now we can easily write a typesafe function that, say, counts the number of nodes in the tree:

fun countNodes(Leaf) = 0 | countNodes(Node(int,left,right)) = 1 + countNodes(left) + countNodes(right)

Read more about this topic:  Tagged Union

Famous quotes containing the word examples:

    “There are many examples of women that have excelled in learning, and even in war, but this is no reason we should bring ‘em all up to Latin and Greek or else military discipline, instead of needle-work and housewifry.”
    —Bernard Mandeville (1670–1733)

    “Histories are more full of examples of the fidelity of dogs than of friends.”
    —Alexander Pope (1688–1744)

    “No rules exist, and examples are simply life-savers answering the appeals of rules making vain attempts to exist.”
    —André Breton (1896–1966)