Live data from Hacker News

Iterators: Signs of Weakness in Object-Oriented Languages

home.pipeline.com

11–12 of 12 posts

Re: Iterators: Signs of Weakness in Object-Oriented Languages

#11
post #5
post #3

While C++0x will have proper lamdbas and closures (I've said this how many times in the past few weeks?), I think it's worth noting the "proper" way to emulate a closure in C++ is with a function object. Example: struct Summation { int& sum; Summation(int& s): sum(s) {} void operator()(int n) { sum += n; } }; vector numbers; int sum = 0; // give numbers some interesting values for_each(numbers.begin(), numbers.end(),…

Interesting. Your comment about C++0x closures inspired me to look it up on Wikipedia. The verbosity of the fragment above is greatly reduced. You had to write 'sum' or 's' lots of extra times ('Summation(sum)', 'sum(s)', 'int& sum', and 'int& s'), and you won't have to do that anymore -- according to wikipedia your function will change in C++0x to: for_each( numbers.begin(), numbers.end(), [&sum](int n) { sum += n;…

Of course, C++ already has std::accumulate, which is basically the same thing as a general fold or a summation, depending on which version you use. So, there isn't really much of a reason to write sum manually at all. :p

http://www.sgi.com/tech/stl/accumulate.html

Re: Iterators: Signs of Weakness in Object-Oriented Languages

#12
It seems odd that he complains about lack of local (modifiable) state while at the same time talking up the advantages of pure functional programming. It's painful to have to explicitly capture state instead of depending on a closure to do it, but you can do it, and somewhat nicely using objects in C++.

Also, is it not right that iterators were introduced in C++ largely to allow generic functions across arrays and other data structures?

Finally, do iterators necessarily imply statefulness? Doesn't seem like it. Taking + 1 as "successor": double sum(const double* start, const double* end) { if (start == end) { return 0.0; } else { return *start + sum(start + 1, end); } }

Post reply on HN