std.sumtype?

SealabJaster sealabjaster at gmail.com
Sun Aug 29 21:09:23 UTC 2021


On Sunday, 29 August 2021 at 19:51:30 UTC, Paul Backus wrote:
>
> ```d
> return exp[0].tryMatch!(
>     (IdentifierExpression exp) => exp.ident
> );
> ```

That's pretty much perfect, thanks!

> But in general, I think this is the wrong approach. What I 
> would do instead is create a helper function like the following:
>
> ```d
> Optional!T maybeGet(T, S)(S s)
>     if (isSumType!S)
> {
>     return s.match!(
>         (T t) => some(t),
>         _ => no!T;
>     );
> }
> ```
>
> This narrows the set of cases you have to deal with from 
> "anything that could be in the `SumType`" to "either `T` or not 
> `T`", and from there you can handle the "not `T`" case however 
> you want--abort, throw an exception, etc.
>
> The general principle here is ["Parse, don't validate."][1]

An interesting way to think about things, which I assume is from 
your apparent experience with functional languages? There's 
definitely a lot to learn from them, even with my limited 
experience with things like F#.

> ```d
> return exp[0].match!(
>     (IdentifierExpression exp) => exp.ident,
>     function string (_) { throw new Exception("..."); }
> );
> ```

I didn't even realise that syntax existed, TIL.

> I agree, this is annoying. My current best solution to this is:

Glad it's not just me, another reason we need this: 
https://forum.dlang.org/post/rj5hok$c6q$1@digitalmars.com

Thanks for your thorough answers.


More information about the Digitalmars-d mailing list