sumtype 0.5.0
Paul Backus
snarwin at gmail.com
Fri Aug 10 19:19:39 UTC 2018
On Friday, 10 August 2018 at 13:11:13 UTC, Everlast wrote:
> On Friday, 10 August 2018 at 12:35:18 UTC, Everlast wrote:
>>
>> It would be nice if some actual examples could be given. The
>> help on dub is a bit confusing because the the code is not
>> complete.
In addition to the example on the dub page, there are a some in
the API docs at https://pbackus.github.io/sumtype/sumtype.html
that go into more detail.
If by "not complete" you mean that they lack a `main` function,
that's because they're defined as `unittest` blocks in the
source. This ensures that they are always correct and up-to-date
with the latest version of sumtype. I hope you will agree that
having to type `void main()` and a couple braces is an acceptable
price to pay for such quality assurance. :)
> Also, I'm curious how one can handle a collection of types with
> match?
>
> Suppose I have SumType!(int, float, string)
>
> and I wanted a generic match on int and float. Something like
>
> (int | float _) => would be awesome, but that is invalid.
>
> [...]
You can do this with a template handler that introspects on the
type of its argument:
(num) {
alias T = typeof(num);
static assert(is(T == int) || is(T == float));
// code to handle int or float goes here
}
If you want nicer syntax, you can factor out the type assertions
into a template wrapper:
SumType!(int, float, string) x;
x.match!(
acceptOnly!(int, float,
num => writeln("number")
),
(string _) => writeln("string")
);
Full code here: https://run.dlang.io/is/MrzF5n
> Also, a full algebra would be nice ;)
>
> alias X = SumType!(int, float, string)
> alias Y = SumType!(complex, vector)
>
> alias Z = SumType.Union(X,Y);
>
> Z is a "super type" as could have been expressed as
>
> alias Z = SumType!(int, float, string, complex, vector).
You can do this already with `alias Z =
SumType!(NoDuplicates!(X.Types, Y.Types));`, using
`std.meta.NoDuplicates`. I don't know of an equivalent template
for getting the intersection of two type sequences, but you could
probably cobble something together with `std.meta.Filter`.
> except, of course, Z would be typed in terms of X and Y.
>
> [...]
What you are describing here is, essentially, an entirely new
type system. It's interesting as a thought experiment, but
ultimately, D already has a type system, and I would much rather
have SumType work with the existing system than invent its own.
(Also, what you call `ProdType` already exists. It's called
`Tuple`, and is located in the module `std.typecons`.)
More information about the Digitalmars-d-announce
mailing list