www.digitalmars.com         C & C++   DMDScript  

digitalmars.D - [Discussion] Usefulness of Algebraic?

reply maik klein <maikklein googlemail.com> writes:
struct Some(T){
     T value;
}
struct None{}

struct Option(T){
     alias OptionAdt(T) = Algebraic!(Some!T, None);
     OptionAdt!T value; //Should default to none
     //OptionAdt!T value = OptionAdt!T(None());
     /*
       Error: memcpy cannot be interpreted at compile time, 
because it has no
       available source code
     */
}

It is a bit unfortunate that the default value of Option!T.init 
is neither Some!T nor None.

Also Algebraic probably has to be wrapped in a struct because D 
can not infer the type of T for the following code.

alias Option(T) = Algebraic!(Some!T, None);

bool test(T)(auto ref Option!T o){
     return true;
}

I really love ADT's but I think that they can not be used as a 
default value limits their usefulness.

/discuss
Feb 13 2016
parent =?UTF-8?Q?S=c3=b6nke_Ludwig?= <sludwig outerproduct.org> writes:
For reference, the TaggedAlgebraic struct that I wrote some time ago 
supports this: https://github.com/s-ludwig/taggedalgebraic

You could do something similar to this:

struct Option(T) {
   struct Kinds(T) {
     typeof(null) none;
     T some;
   }
   TaggedAlgebraic!Kinds data;
   alias data this;
    property bool hasValue() const
     { return data.kind == TaggedAlgebraic!Kinds.Kind.some; }
}

void test()
{
   Option!int opt;
   assert(!opt.hasValue);
   opt = 12;
   assert(opt.hasValue);
   assert(opt == 12);
}
Feb 13 2016