"Andrei Alexandrescu" <seewebsiteforem...@erdani.org> wrote in message news:gmgb9u$qk...@digitalmars.com... >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 haven't looked at any of the replies yet, and euclidean distance and Ranges are things I'd have to look up (I haven't actually had a chance to look at the Range docs), but I would do something like this: double euclideanDistance(Range)(Range a, Range b, double limit) { limit *= limit; double result = 0; bool foundIt=false; for (; !a.empty && !foundIt; a.next, b.next) { enforce(!b.empty); auto t = a.head - b.head; result += t * t; if (result >= limit) { foundIt = true; break; // This line needed? } } if(!foundIt) // This line needed? enforce(b.empty); return sqrt(result); }