Option types and pattern matching.

cym13 via Digitalmars-d digitalmars-d at puremagic.com
Sat Oct 24 23:45:45 PDT 2015


On Sunday, 25 October 2015 at 05:45:15 UTC, 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.");
> }
>
> 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.

Although it doesn't exactly fit the problem at hand I'd like to 
mention
predSwitch. For most cases it does what you could expect from 
pattern
matching I think. Here is an example showing its strength and 
limits on your
showcase:

     import std.conv;
     import std.stdio;
     import std.algorithm.comparison;
     import std.variant;


     void main(string[] args) {
         Variant x;

         x = 42;

         if (x.hasValue) {
             x.predSwitch!((a,b) => *a.peek!int == b) (
                 7,  "Lucky number!",
                 42, "This should be a lucky number too!",
                 "No luck, the number was " ~ x.to!string
             ).writeln;
         }
         else {
             writeln("No value");
         }
     }


More information about the Digitalmars-d mailing list