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

Andrei Alexandrescu andrei at erdani.com
Tue Jan 12 19:54:01 PST 2010


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.

> Since I read through a draft, I would also like to suggest that
> another topic will need to be discussed in the final edition:
> error handling.

I'm trying to make time for that too.


Andrei


More information about the dmd-concurrency mailing list