Option types and pattern matching.

TheFlyingFiddle via Digitalmars-d digitalmars-d at puremagic.com
Mon Oct 26 09:42:26 PDT 2015


On Monday, 26 October 2015 at 15:58:38 UTC, Edmund Smith wrote:
> On Monday, 26 October 2015 at 14:13:20 UTC, TheFlyingFiddle 
> wrote:
>> On Monday, 26 October 2015 at 11:40:09 UTC, Edmund Smith wrote:
>>> Scala's Option is really nice on the other hand since you 
>>> can/should pattern match).
>> Don't really see a point in an optional type if can access the 
>> underlying
>> value without first checking if it's there.
>
> The key difference with (exhaustive) pattern matching is that 
> it *is* the check that the value is there. Pattern matching 
> enforces the existence of an on-nothing clause for Optional, 
> on-error for Error, on-Leaf and on-Branch for Bintrees, etc.
> And even with nice higher-order functions, plain pattern 
> matching is quite valuable for finely controlled error/resource 
> handling, and I often see it in Rust code as well as Scala (and 
> I've seen it used in Haskell occasionally too). A brief, 
> contrived example use-case:

What I meant is that I don't really see the point in optionals 
that look something like this:

struct Optional(T)
{
    T value;
    bool empty;

    ref T get()
    {
       enforce(!empty, "Value not present!");
       return value;
    }

    //Stuff...
}

Optional!(int[]) doSomething(...);
void process(int[]);

void foo()
{
     Optional!(int[]) result = doSomething(...);
     process(result.get());
}

I mean sure you get a null check in foo instead of in process but 
this style of writing code does not really give you much of an 
advantage since you can't really handle the errors much better 
then you could a Null exception.

If you instead use pattern matching as in your example you have 
much better context information that can actually help you do 
something in the case a value is not there.


More information about the Digitalmars-d mailing list