February 13, 2016 [Discussion] Usefulness of Algebraic? | ||||
---|---|---|---|---|
| ||||
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 |
February 13, 2016 Re: [Discussion] Usefulness of Algebraic? | ||||
---|---|---|---|---|
| ||||
Posted in reply to maik klein | 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); } |
Copyright © 1999-2021 by the D Language Foundation