Primus2\Falcraft: New Data Type (tagged union)

IMPORTANT

This code is obsolete and has moved to another project, asherwunk/phabstractic.  For more information on the most recent version see the current blog post.

Primus/Falcraft now has support for a tagged union data type.

Tagged Union

Tagged unions are also called sum type, disjoint union, discriminated union, and variant (record). A tagged union here is a value that can only hold specific types of values, but may be any one of these types of values can be stored at any one time. Only one of the types can be in use at any one time, and an object property explicitly indicates which one is in use. This creates a form of “data structure polymorphism” where a value is of a specific type, rather than a is_a relationship. Tagged unions are most important in functional languages such as ML and Haskell. For more information on this somewhat obscure data type please see the Wikipedia article.

Implementation

Using the Restrictions Predicate Data Type (github) we can easily set up a tagged union class. A tagged union must identify its type, its value and its type restrictions. The type restrictions are set on the construction of a tagged union data structure. The code for these looks like:

Checking Value Types

The heart of the tagged union lies in the setting of the value. When the value is set it must comply with the restrictions placed on the tagged union at construction. The code for that looks like:

We use the typing functions (github) provided by the Falcraft Data Types library to obtain the type of the piece of data coming in. All values should be typeable, so it is rare to incur a type error (you must really be doing something bizarre). Then we check to see if that type is allowed in the restrictions, and if so, set it.

Conclusion

To quote Wikipedia in the above article:

Many programming techniques and data structures – including rope (data structure), lazy evaluation, class hierarchy (see below), arbitrary-precision arithmetic, CDR coding, the indirection bit and other kinds of tagged pointers, etc. – are usually implemented using some sort of tagged union.

Tagged unions are useful data types for systems such as artificial intelligence, where knowledge frames might be of many different types (coming from different systems).

photo credit: cover1 via photopin (license)

Liked it? Take a second to support kadar on Patreon!

kadar

I'm just a wunk, trying to enjoy life. I am a cofounder of http//originalpursuitssoc.com/ and I like computers, code, creativity, and friends.

You may also like...

Leave a Reply

%d bloggers like this: