OT: CS education gone wrong (Was: Re: TDD is BS?)

Adam D. Ruppe destructionator at gmail.com
Sat Jun 22 12:28:00 PDT 2013


On Saturday, 22 June 2013 at 16:38:31 UTC, Andrei Alexandrescu 
wrote:
> It's still buggy.

What's the test case? I also forgot the empty string, blargh. 
Let's scrap it.

> Overly complicated, too - at 21 lines, it's about twice as 
> large as the canonical implementation.

Huh, even the shortest impl I can think of is about the same 
length:

inout(char)* mystrstr(inout(char)* haystack, const(char*) needle) 
{
         assert(haystack !is null);

         if(needle is null)
                 return haystack;

         while(*haystack) {
                 auto h = haystack;
                 const(char)* n = needle;
                 while(*n == *h && *n && *h) {
                         h++;
                         n++;
                 }
                 if(*n == 0)
                         return haystack;
                 haystack++;
         }

         return null;
}


I like this a lot better because it is more straightforward. My 
first draft was trying to avoid looking at the same character 
twice, but obviously that didn't work so fixing that ended up 
doing the same thing as this anyway. I guess better to KISS than 
be embarrassingly wrong, eh?


You could do it in about ten lines like this:

inout(char)* mystrstr(inout(char)* haystack, const(char*) needle) 
{
         while(*haystack) {
                 auto h = haystack;
                 const(char)* n = needle;
                 while(*n == *h && *n && *h)
                         h++, n++; // LOL COMMA OPERATOR
                 if(*n == 0)
                         return haystack;
                 haystack++;
         }
         return null;
}


But I really like the null check. Yes, I know the hardware does 
it, but it is a pain in the butt to fire up a debugger when a 
null hits you in the middle of something. The nice assertion 
failure message is so much faster to handle.


More information about the Digitalmars-d mailing list