I've checked assembly output at many optimization levels with both gcc 4.8.1 and clang 3.4.190255, no tail call optimization for this kind of code.
Any special reason why collatz_aux
doesn't get a tail call optimization?
#include <vector>
#include <cassert>
using namespace std;
vector<unsigned> concat(vector<unsigned> v, unsigned n) {
v.push_back(n);
return v;
}
vector<unsigned> collatz_aux(unsigned n, vector<unsigned> result) {
return n == 1
? result
: n % 2 == 0
? collatz_aux(n / 2, concat(move(result), n))
: collatz_aux(3 * n + 1, concat(move(result), n));
}
vector<unsigned> collatz_vec(unsigned n) {
assert(n != 0);
return collatz_aux(n, {});
}
int main() {
return collatz_vec(10).size();
}
The destructor for the vector<unsigned>
parameter needs to be called after the return.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With