środa, 13 sierpnia 2008

With C++

C++ has lack of everything useful, you won't find local functions for example. But I really miss Pascal with statement. I know people say that would confuse programmer or even compiler. Wait! Pascal programmers were not confused, Pascal compilers were able to deal with this. Moreover, C++ programmers are not confused with tons of nested name spaces, crazy visibility rules and other odds.

Here is a snippet from my program:
for (unsigned i=0; i < data.measure_dist.size(); i++)
if (data.measure_dist[i].active)
Using with would make this much clearer:
for (unsigned i=0; i < data.measure_dist.size(); i++)
with (data.measure_dist[i]) {
if (active)
find_crosspoints(point_1, point_2, outline, crosspoints);
Does anybody confused about this code? Does anybody don't know what above code do? I don't think so.

Lets continue. With could also accept more complex syntax and allow temporary rename different entities. This (inefficient!) code finds all intersection between two sets of segments:
double u, v; // parameters, lerp(A, B, u) = A + u*(B-A)
for (int i=0; i < data.points.inner.size() - 1; i++)
for (int j=0; j < data.points.outer.size() - 1; j++) {
bool b = intersection(
u, v);

if (b)
crosspoints.add(lerp(data.outline.inner[i], data.outline.inner[i+1], u));
Now compare with following code:
double u, v;
with (data.points) {
with (inner as A, outer as B) {
for (int i=0; i < A.size() - 1; i++)
for (int j=0; j < B.size() - 1; j++)
if (intersection(A[i], A[i+1], B[i], B[i+1]))
crosspoints.add(lerp(A[i], A[i+1], u));
Code is easier, cleaner, compacted. In next posts I will show some other ideas.