Generalized switch statement (a la pattern matching)

bearophile bearophileHUGS at lycos.com
Fri Oct 28 02:33:06 PDT 2011


Norbert Nemec:

> Where is the fundamental advantage compared to the following?
> 
> if(x == "foo") writeln("got foo")
> else if(x == "foo") writeln("got foo")
> else if(x == "foo") writeln("got foo")
> else assert(false);

The advantages are visible even with the D final switch, but are more generalized. The various cases are formatted nicely with less syntax noise, this allows you to see them better. And the compiler gives an error if you duplicate cases, or if some cases are missing.

This is also useful if you modify the data structures themselves (adding or removing cases); the compiler gives errors for all the patterns you have to fix after the change. This helps write correct code both the first time, and later during code updates.

Regarding pattern matching in D, I'd like a "just" improvement of D switches:
http://d.puremagic.com/issues/show_bug.cgi?id=596

Bye,
bearophile


More information about the Digitalmars-d mailing list