std.sumtype?
Atila Neves
atila.neves at gmail.com
Thu Mar 25 14:28:06 UTC 2021
On Tuesday, 23 March 2021 at 16:29:52 UTC, Steven Schveighoffer
wrote:
> 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).
I don't think this is enough of a reason.
> 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.
This is the part I don't get. Why would one want to do that? To
me this feels like checking for the dynamic type of an object in
OOP, in the sense that if you're doing that you're probably doing
something wrong.
> 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?
The former.
> Which performs better?
It shouldn't matter - performance considerations in the absence
of running a profiler are futile. If nobody notices, it doesn't
matter. If someone noticed, a profiler gets run and the code
optimised where it's actually slow.
Having said that, I think that if there are two alternatives to
getting the job done, and the two are equally
readable/maintainable, prefer the fastest one. Or as
Sutter/Alexandrescu once wrote, "belated pessimization is the
root of no good".
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);
If one wants to do that sort of thing, yes, this is nicer. I'm
still at a loss as to why one would *want* to do such a thing.
I think it's useful to remember that in languages where sum types
and pattern matching are features there's no way to do this.
More information about the Digitalmars-d
mailing list