Option types and pattern matching.

Nerve via Digitalmars-d digitalmars-d at puremagic.com
Sat Oct 24 22:45:13 PDT 2015


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.


More information about the Digitalmars-d mailing list