Fast switching..

Sean Kelly sean at invisibleduck.org
Wed Jun 11 08:04:52 PDT 2008


== Quote from Georg Wrede (georg at nospam.org)'s article
> Regan Heath wrote:
> > Hi all,
> >
> > I've been AWOL from this NG for a while but recently a friend of mine
> > sent me a link to this:
> > http://blogs.msdn.com/jomo_fisher/archive/2007/03/28/fast-switching-with-linq.aspx
> >
> > and my first thought was; can something similar (or even better) be done
> > in D. :)
> >
> > I admit, I haven't even spent 5 mins thinking about how I might do it,
> > but I've never been particularly good with the compile time features of
> > D so I figured I'd post something here and see what the people who are
> > good at it can come up with.
> >
> > So, consider this a little challenge .. it may turn out to be trivial,
> > it might not, I have no idea.
> A language that allows you to write switch statements with strings
> should have this built-in. But that is actually a quality of
> implementation issue, and therefore transparent to the spec.
> In real life, if I were to tackle this and there were less than two
> dozen words, I'd figure it out manually. This would also allow for
> optimizations, like if I expect some of the words to occur more often
> than others.

I've done this quite often with simple parsers:

switch( token[0] )
{
case 'o':
    if( strcmp( token, "one" ) )
        throw new ParseFailure();
    // blah
    break;
case 't':
    if( !strcmp( token, "two" ) )
        // stuff for "two"
    else if( !strcmp( token, "three" ) )
        // stuff for "three"
    break;
}

It's easy enough to do it all with switch statements as well, but I
like the insurance that checking the entire string provides.  It would
be nice if DMD optimized string-based switch statements this way.
I'll admit to being a bit old-school in this respect--I've never actually
used string switch statements in D.


Sean



More information about the Digitalmars-d mailing list