by crawshaw · 12y ago · 0 comments
He made a good case that anywhere you have a non-trivial loop in C++, you're almost always going to be better off folding the problem in to a composition of algorithms. The code got more readable, more performant, and redundant code can often be removed.
Please take an hour to watch it here in glorious high quality:
http://channel9.msdn.com/Events/GoingNative/2013/Cpp-Seasoni...
squareVec4 is simple, concise, and leaves little to no room for ambiguity. squareVec6 is a monstrosity that requires reading more text that contains more complicated ascii and involves more concepts.
And for the author to then claim that making use of "cool stuff" in <algorithm> is more maintainable code? That's just crazy talk man!
return v.fold([], def (acc, i) { acc.push(i*i) });
Or better: return v.map(def(i) { i * i })
Something like 'map' in this case is much more appropriate, since it's operation on a collection which returns a new collection with a given operation applied on each element.If you want something that's both concise and readable, try the Python list-comprehension version. That is an elegant solution. The C++ accumulate/transform solutions are the very opposite of elegant. In a code review, I would flag them as obfuscatory.