Algebraic Data Types in D?

Sönke Ludwig via Digitalmars-d digitalmars-d at puremagic.com
Thu Jul 31 07:40:55 PDT 2014


Am 31.07.2014 13:42, schrieb Remo:
> http://tech.esper.com/2014/07/30/algebraic-data-types/
>
> D already has product type it is struct.
> But D lacks sum type also called tagged-union.
>
> Do you think it would be possible to add something like this to D2 ?

I'm currently in the process of polishing one up to improve vibe.d's 
Json/Bson type implementations. It's definitely possible to do (I've 
been using one for years), but has its caveats when there are dependency 
cycles in the code.

Just to make clear what the difference is:

  - "Variant": open set of types, using TypeInfo for identification
  - "Algebraic": closed set of types, using TypeInfo for identification
  - Tagged union: closed set of types with a numeric  ID for each type

The latter has a few advantages in some situations

  - Doesn't require type info
  - Can use "switch" instead of iterating over all possible types or 
storing a pointer to helper functions for dealing with the type
  - Allows to use "final switch" to guarantee handling all cases
  - Provides a handy type value that can be used and stored in user code 
(vs. passing and storing TypeInfo instances)
  - Could be made to store the same type with different IDs



More information about the Digitalmars-d mailing list