Discriminated Unions

Timon Gehr timon.gehr at gmx.ch
Tue Nov 19 14:31:33 PST 2013


On 11/19/2013 12:55 AM, Stretto wrote:
> F# now has Discriminated Unions:
>
> http://msdn.microsoft.com/en-US/library/dd233226.aspx
>
> Would it be possible to have something similar in D?

Sure. DMD still refuses to compile my proof of concept implementation 
though:

https://d.puremagic.com/issues/show_bug.cgi?id=10431
https://d.puremagic.com/issues/show_bug.cgi?id=11558

In essence, the following is easily possible in theory:

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

auto list(R)(R r) if(isInputRange!R){
     if(r.empty) return Nil!(ElementType!R);
     auto f = r.front;
     r.popFront();
     return Cons(f,list(r));
}

size_t length(T)(List!T l){
     return l.match!(
         ()=>0,
         (x,xs)=>1+length(xs)
     );
}


More information about the Digitalmars-d mailing list