Discriminated Union

Most, if not all, FunctionalProgrammingLanguages have discriminated unions as a fundamental building block. It's not about saving space. I wrote one paper and three articles on implementing discriminated unions in CeePlusPlus, and http://www.boost.org has an implementation of discriminated unions that builds on those ideas.

-- AndreiAlexandrescu (on news:comp.lang.c++.moderated)


...a discriminated union is?

One example is a ComVariant.

In short, in C-style CeePlusPlus, it is this:

  struct var {
     union { int i; double d; char *s; } u;
     enum { VT_NULL, VT_INT, VT_DOUBLE, VT_STRING } vt;
     };

Combined with a set of appropriate functions to access those members smartly, a DiscriminatedUnion is how you implement a typeless system, or a system with strong type checks at runtime.

Given a language like Ruby, consider this variable:

 v = 12
 v = 12.1
 v = "12"

The same internal variable received each value. Then it cleared its union, set one member to the value, and set the discriminating type to the 'vt' variable.

If Ruby were weakly typed, you could say this:

 v = 12
 assert "12" == v

But Ruby is strongly typed, so you must explicitely state what goes on under the covers in a weak language:

 assert "12" == v.to_s()

All soft languages have a DU at their heart. ComVariant began life as MS's private implementation of a BASIC variant type.


EditText of this page (last edited May 28, 2004) or FindPage with title or text search