[dmd-concurrency] Pattern matching on message receives, error handling

Sean Kelly sean at invisibleduck.org
Tue Jan 12 20:38:05 PST 2010


On Jan 12, 2010, at 7:54 PM, Andrei Alexandrescu wrote:

> Mark Kegel wrote:
>> Call me silly, but how many of you have seen 1000 line switch
>> statements when polymorphism was called for? And what is
>> polymorphism but dispatch / pattern matching over argument type?
>> So when I see code like this:
>>       auto msg = receiveOnly!(Tid, int)();
>>       if (!msg[0]) return;
>>       writeln("Secondary thread: ", msg[1]);
>>       msg[0].send(thisTid);
>> ...where you the first thing you tell new readers about how to
>> test what message you just got is with an 'if' statement, I get
>> scared. Please give users a more elegant mechanism, and if you
>> need ideas about what it could look like I would suggest that
>> Scala offers a passable (and maybe even compatible) syntax.
> 
> You have a point, but quite a weak one. First, the example above is not illustrative on the pattern matching capabilities of D; we'll get to those with the full-fledged receive() function. For now I just considered fine to send a null Tid to signal loop termination. With receive() you can dispatch to various functions depending on the types of the arguments. With introspection it's very easy to dispatch messages to an object depending on their types.
> 
> I don't agree with the comparison with switch() vs. virtuals at all. The problem with switch() is that it breaks modularity by requiring all cases to be present in the same place. On the contrary, pattern matching _also_ requires all cases to be present together (which makes me believe it's much less powerful than it's cracked to be). So if I pattern match with
> 
> patternmatch (receive()) {
>    case int x: ...
>    case (string a, int b): ...
> }
> 
> versus
> 
> receive(
>    (int x) { ... },
>    (string a, int b) { ... }
> );
> 
> we're only talking about a difference in syntax, not power. So essentially you shouldn't be scared just because there's no built-in syntax for something that can be expressed within the existing language with the same power.

It's worth adding that Erlang does provide pattern matching capabilities that have to be a run time in D, but I'm not sure this same capability is available in Scala, for example.  In our case, this will probably be handled manually by the user, with possibly some fancier way to do it later (metaprogramming can do quite a lot in D).  For example:

    receive(
        (int x) { ... },
        (string a, int b) { if (a == "blah") return false; ...; return true; }
    );

Here, the second function checks string a to see if it matches a pattern, and returns true/false to indicate that there was a match.



More information about the dmd-concurrency mailing list