draft proposal for Sum Types for D
rikki cattermole
rikki at cattermole.co.nz
Tue Nov 29 13:21:25 UTC 2022
"Which one is existing is specified by a hidden field called a tag."
Actually I recommend against hiding the field. Make it able to be the
first member of a struct, that way the struct can be effectively zero sized.
"Members of a sum type can either have integer values assigned
sequentially by the implementation, unique integer values assigned by
the programmer, or be values of a specified type."
I know it seems like its a good idea, but this was a key idea that Jacob
came up with for value type exceptions, use a hash instead. Although
allowing custom values is a good idea.
Consider:
```d
SumType!(int, long, float, double) first() {
return second();
}
SumType!(int, float) second() {
return typeof(return).init;
}
```
In this example you have to inspect and convert every entry manually to
the other returned sumtype even though it was a superset. There is no
reason in the theory that this shouldn't work and it does look like it
should.
"Members of sumtypes cannot have copy constructors, postblits, or
destructors."
Kills reference counting, can't use it. Can't use it for value typed
exceptions as the underlying sum type implementation. Not good enough.
Note when these are not defined you can optimize the copying to be just
mov's.
"sumtype Option(T) = None | Some(T);"
Supporting ML-ish style syntax is a must. It gives us one liners and it
helps with on boarding those with familiarity with the source material.
My bet is a lot of people will prefer it when they are not worried about
documenting each member.
"Sumtypes do not implicitly convert to any other types. Nor can they be
cast."
They must cast implicitly to supersets. See above.
"Special Case for Non-Null Pointers"
Okay but how do we disallow null pointers? ``@disable`` the Null member
perhaps?
Finally there needs to be a way to remove a member of a sumtype i.e.
```d
SumType!(int) first() {
return second().removeMember!int;
}
SumType!(int, float) second() {
return typeof(return).init;
}
```
This is equivalent to the try/catch statement in a value type exception
as far as the sumtype is concerned.
Good start though!
https://github.com/rikkimax/DIPs/blob/value_type_exceptions/DIPs/DIP1xxx-RC.md
More information about the Digitalmars-d
mailing list