Option types and pattern matching.

Rikki Cattermole via Digitalmars-d digitalmars-d at puremagic.com
Sat Oct 24 22:53:29 PDT 2015


On 25/10/15 6:45 PM, Nerve wrote:
> On Sunday, 25 October 2015 at 05:05:47 UTC, Rikki Cattermole wrote:
>> Since I have no idea what the difference between Some(_), None and
>> default. I'll assume it's already doable.
>
> _ represents all existing values not matched. In this case, Some(_)
> represents any integer value that is not 7. None specifically matches
> the case where no value has been returned. We are, in most languages,
> also able to unwrap the value:
>
> match x {
>      Some(7) => "Lucky number 7!",
>      Some(n) => "Not a lucky number: " ~ n,
>      None => "No value found"
> }
>
> Or something to that effect. The equivalent switch statement right now
> would be:
>
> if (x.hasValue()) {
>      switch (*x.peek!(int)) {
>          case 7:    writeln("Lucky number seven!"); break;
>          default:   writeln("Not a lucky number: ", *x.peek!(int)); break;
>      }
> } else {
>      writeln("No value.");
> }

I'm pretty sure e.g. opEquals/opCmp should work here.
Shouldn't need to switch upon a primitive type. Theoretically could do 
it on a e.g. struct. Which has the special comparison that you want.

> This does not return a value (is a procedural structure); the switch
> cannot match null; in order to unwrap, we must call peek() again; and
> between the extra if-else and the break statements, this is not as clean.
>
> As a note, pattern matching could almost be considered an extended form
> of the ?: operator, which matches over value cases rather than boolean
> truthiness.
>
> Apologies if this is all below you, I'm not in Andrei's or Walter's
> league, just an interested party trying to make suggestions to better
> the language.

No no it's fine. Only this morning I was toying with the idea of 
variable length struct's on IRC. Turns out, wouldn't really work.


More information about the Digitalmars-d mailing list