goto

Derek Parnell derek at psych.ward
Thu Feb 5 22:08:33 PST 2009


On Thu, 05 Feb 2009 19:37:35 -0800, Andrei Alexandrescu wrote:

> I was coding a simple Euclidean distance function with limit:
> 
> double euclideanDistance(Range)(Range a, Range b, double limit)
> {
>      limit *= limit;
>      double result = 0;
>      for (; !a.empty; a.next, b.next)
>      {
>          enforce(!b.empty);
>          auto t = a.head - b.head;
>          result += t * t;
>          if (result >= limit) goto thatsit;
>      }
>      enforce(b.empty);
>    thatsit:
>      return sqrt(result);
> }
> 
> How would an elegant goto-less approach look like? It should not 
> duplicate code, e.g. the call to sqrt.

I'm not sure about the elegant part but ...

double euclideanDistance(Range)(Range a, Range b, double limit)
{
     limit *= limit;
     double result = 0;
     do
     {
         -- Precondition for next iteration; 'a' ought not be empty.
         if (a.empty)
         {
             -- If it is empty then 'b' must also be empty.
             enforce(b.empty);
             -- No more work needs be done.
             break;
         }

         -- If 'a' isn't empty then 'b' must not be empty.
         enforce(!b.empty);

         -- Perform this iteration's work.
         auto t = a.head - b.head;
         result += t * t;

         -- If the limit has been reached then stop working.
         if (result >= limit)
            break;

         -- Move along to the next element pair.
         a.next;
         b.next;

         -- And repeat.
     } while (true);
     
     return sqrt(result);
}



-- 
Derek Parnell
Melbourne, Australia
skype: derek.j.parnell



More information about the Digitalmars-d mailing list