Optional and NotNull version 0.5.0 - swift optional like and scala option like
Paul Backus
snarwin at gmail.com
Fri Aug 24 22:37:30 UTC 2018
On Friday, 24 August 2018 at 20:59:34 UTC, aliak wrote:
> THis is true. And might be interesting to try out actually. Can
> you access the types in a SumType via index?
>
> I'm thinking because Optional behaves like a range, and I guess
> I'd define a SumType!(T, None), then a rough outline may be:
>
> struct None {}
> immutable none = None();
>
> struct(T) {
> SumType(T, None) opt;
> T front() {
> return opt[0]; // what to do here?
> }
> }
>
> Or I guess I should maybe do it like this?:
>
> return opt.match!(
> (T val) => val,
> (None) => T.init,
> );
I think this is probably the best way:
@property T front() {
return opt.match!(
(T val) => val,
(None) {
assert(false, "called .front on an empty range");
return T.init; // for return type inference
}
);
}
You could also do it with `tryMatch` and
`std.exception.assertNotThrown`. It makes the code a little
nicer, but involving exceptions at all seemed like unnecessary
overhead to me.
More information about the Digitalmars-d-announce
mailing list