std.sumtype?
Steven Schveighoffer
schveiguy at gmail.com
Tue Mar 23 16:29:52 UTC 2021
On 3/23/21 10:45 AM, Atila Neves wrote:
> On Friday, 19 March 2021 at 07:28:19 UTC, drug wrote:
>> On 3/18/21 9:42 PM, Oleg B wrote:
>>>
>>> but read-only tag (kind, type index) is key feature in chouse between
>>> sumtype and other for me, and I hope it will be added before next
>>> compiler release...
>>>
>>
>> Totally agree, it is an important feature.
>
> Can anyone explain to me why?
1. It costs nothing (returning tag is pretty much free).
2. reasoning about things to do with a SumType without having to
generate (possibly) an entire set of handler functions allows different
designs or writing code in more efficient/straightforward ways.
Consider an assert that validates a SumType is a certain type:
SumType!(string, float, int) someType;
...
someType.match!((T t) {assert(is(T == int)); });
vs.
assert(someType.typeIndex == 2);
Which looks better? Which performs better? For the first case, all the
types have to be used to build the lambda, which means 4 more functions,
and the match call has to basically do a switch on all possible tags,
and call the right function, which then throws an assert error or not.
Or, without asserts enabled, builds 4 functions empty functions which
hopefully are inlined.
The second implementation checks if an integer equals 2. Or if asserts
are disabled, elides the whole statement. Only drawback I see is it's
very dependent on the type not changing indexes.
All that said, the taggedalgebraic project looks nicer to me:
union Values
{
string String;
float Float;
int Integer;
}
TaggedAlgebraic!(Values) algType;
...
assert(algType.kind == algType.Kind.Integer);
-Steve
More information about the Digitalmars-d
mailing list