3 ms·
Such functional code in C++ doesn't need to be bad. Though I would have coded it a bit different: int Dice::total() const { return sum(dice.begin()
by albertzeyer 16y ago
Such functional code in C++ doesn't need to be bad. Though I would have coded it a bit different:
int Dice::total() const {
return sum(dice.begin(), dice.end(), _1 ->* &Dice::faceValue());
}
with:
template<typename T, typename Iter>
T sum(Iter begin, Iter end, function<T (Iter)> f = *_1) {
if(begin != end)
return sum(next(begin), end, f) + f(begin));
return 0;
}
This allows some more flexibility. For example, you could also provide other implementations of sum. You could also easily make your code threaded without changing the code of Dice::total (well, take this example a bit carefully -- of course it implies that faceValue() is threadsafe and also does only make sense if faceValue is expensive to call).
Summing up some numbers may be anyway not the best example for this because the naive implementation is really so short and trivial and in most cases enough.
- ramchip 16y agoTail call optimization is not guaranteed for optimized C/C++ programs, and is not done at all in debug mode, so this kind of implementation can cause trouble with large structures. I used to have fun, too, implementing tail-recursive functions to do stuff like flashing a LED on microcontrollers. I have since recovered :) It is also my experience that helper functions like "sum" tend to be used very few times, and need a lot of variations, so it's actually better to just write the loop when needed. The theoritically advantageous functional programming is hard to convey into C++. Syntax and other technical reasons are partly to blame, but the biggest has to be simply the culture. Very few C++ coders think functionally, and coding, especially in C++, tends to be a team job...
- albertzeyer 16y agoThe tail recursion was not my point. I also could have given another implementation of sum. I wanted to demonstrate that the implementation of Dice::total() can be much clearer and still in a similar functional way.