On Sunday, 30 September 2018 at 22:17:05 UTC, aliak wrote:
On Saturday, 29 September 2018 at 19:27:29 UTC, Paul Backus
wrote:
I agree that this is useful, but why not just return a naked
`SumType!(string, JSONError)` in that case? Is there some
additional value added by the `Expect` wrapper that I'm not
seeing?
That's an option as well I guess. But then you'd need to rely
on convention and you couldn't do SumType!(int, int) f(), and
Expect also gives you some more purposeful APIs that makes the
code's intent clear. Plus I'm considering range behavior as
well.
Is being able to write `Expect!(int, int)` actually desirable,
though? It seems to me like being forced to write something like
`SumType!(int, ErrorCode)` to distinguish the two cases would be
a good thing, even if ErrorCode itself is just a renamed int
(e.g., `struct ErrorCode { int code; alias code this; }`).
I guess you could argue that `return
typeof(return).unexpected(...)` is better than `return
typeof(return)(ErrorCode(...))`, which is what you'd get with
SumType, but they look equally ugly to me. What's really needed
to make that look nice is implicit constructors.
Treating an Expect as a range basically turns it into an
Optional, in the sense that it collapses any error information it
contains down to the boolean of empty vs not-empty. In fact,
probably the easiest way to add range behavior to Expect would be
to add a method that returns an Optional containing the expected
value, since Optional already has range behavior.
Could you also return a union voldermort type then instead of a
SumType?
Raw unions in D are horrifically unsafe, so I wouldn't recommend
it. If you want a voldemort SumType, you can get one like this:
auto f()
{
struct Result { SumType(T, U) data; alias data this; }
return Result(...);
}