Option types and pattern matching.

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


On 25/10/15 7:15 PM, Rikki Cattermole wrote:
> On 25/10/15 7:05 PM, Nerve wrote:
>> On Sunday, 25 October 2015 at 05:53:32 UTC, Rikki Cattermole wrote:
>>> 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.
>>
>> Hm...these are boolean operators. This means we can only compare two
>> cases at a time, does it not? Negates the strength of a switch/pattern
>> match, unless there's something I'm missing.
>
> Well you only need to compare two cases.
> I need to spend a bit of time, to see if what I think can be done, is
> actually possible. Essentially toying with your 'Some' types comparison
> rules.
>
>> What are these variable length structs you mention, and their special
>> comparisons? How would we use them?
>
> Oh the idea was a complete flop. It's just an example of how welcoming
> ideas are. Just no guarantee they'll make it to even a consideration
> from Walter.

Just alter the value in v1 under the main function, to see the different 
behaviors.

It's slightly backwards, you expect what is default to be a case. I'm 
sure you can handle changing the logic of opEquals to be what you want.

Also to get a version of Foo that has haveVal as false, probably should 
be a static method, instead of that custom usage. Not to mention 
templating it ext. ext.

struct Foo {
         int val;
         bool haveVal = true;

         alias val this;

         bool opEquals(Foo f) {
                 if (haveVal == f.haveVal) {
                         if (haveVal)
                                 return val == f.val;
                         else
                                 return true;
                 } else
                         return false;
         }
}

void main() {
         import std.stdio : writeln;
         Foo v1 = Foo(0, false);

         switch(v1) {
                 case 8:
                         writeln(9);
                         break;
                 case 6:
                         writeln(6);
                         break;
                 case Foo(0, false):
                         writeln("no value");
                         break;
                 default:
                         writeln("unknown: ", v1.val);
                         break;
         }
}



More information about the Digitalmars-d mailing list