On Monday, 1 October 2018 at 00:51:24 UTC, Paul Backus wrote:
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; }`).
Hard to say, I would try to avoid it if possible, but why should
it not be allowed if someone wants it? For now it feels like an
opinionated restriction that I think is better left out of
generic code when possible - at least for now. If it turns out
otherwise I'll change it - this is all still quite experimental
in me head.
Using SumType to denote success and failure would be more of a
convention though and would make for more "huh?" moments for
readability/maintainability, IMO. I like typing intents.
And being able to add an "alias this" in Expect for e.g. might be
nice. Or if I want to add a "make match has exactly two handlers"
so that you have to handle both cases would also be a plus.
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.
*nods*
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.
Good point. Agreed!
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(...);
}