Algebraic Data Types in D?

Timon Gehr via Digitalmars-d digitalmars-d at puremagic.com
Thu Jul 31 17:35:33 PDT 2014


On 07/31/2014 06:23 PM, Andrei Alexandrescu wrote:
> On 7/31/14, 6:03 AM, w0rp wrote:
>> On Thursday, 31 July 2014 at 11:42:21 UTC, Remo wrote:
>>> 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 ?
>>
>> There is a library solution for this in the standard library.
>>
>> http://dlang.org/phobos/std_variant.html#.Algebraic
>>
>> It doesn't handle recursive types at the moment, like alias Foo =
>> Algebraic!(Foo[]). Apart from that, it should be what you are looking
>> for.
>
> alias Foo = Algebraic!(This[]);
>
> Andrei

alias Foo = Algebraic!(int,Algebraic!(Foo[],double)[]);

There is also this kind of approach:

mixin ADT!q{
  List(T):
  | Nil
  | Cons T List!T
};


Of course, product types ("tuples") and sum types ("tagged unions") and 
recursive types are elementary enough to be proper language features in 
one way or another with all the syntactic convenience that yields for 
pattern matching.


More information about the Digitalmars-d mailing list