I'm trying to implement Ackerman function using a tuple
of unsinged long long
This is the line that i'm trying to create
A(m, n) = A(m - 1, A(m, n - 1))
So here is my code:
uint_type calculate(tuple_type const& args) const {
uint_type retval;
uint_type retval;
auto second = make_tuple(m - 1, calculate(make_tuple(m, n - 1)));
auto first = make_tuple(m - 1, second);
retval = calculate(first);
return retval;
}
};
and here is the error:
error: no viable conversion from 'tuple<[...], std::__1::tuple>' to 'const tuple<[...], uint_type>' retval = calculate(firstTuple);
^~~~~~~~~~emphasized text
Type errors are sometimes hard to find if you use a lot of auto
and template functions like make_tuple
. Here's how you'd write it with less use of auto
and make_tuple
:
uint_type calculate(tuple_type const& args) const {
const uint_type m = get<0>(args);
const uint_type n = get<1>(args);
uint_type retval;
tuple_type second{m - 1, calculate(tuple_type{m, n - 1})};
tuple_type first{m - 1, second};
// ^^^^^^ error
retval = calculate(first);
return retval;
}
You can see how adding a couple type annotations moved the error message exactly to where the error is.
However, that's not the Ackermann function. This is the Ackermann function:
uint_type calculate(tuple_type args) const {
const uint_type m = get<0>(args);
const uint_type n = get<1>(args);
if (m == 0)
return n + 1;
if (n == 0)
return calculate(tuple_type{m - 1, 1});
return calculate(tuple_type{m - 1, calculate(tuple_type{m, n - 1})});
}
Note that the tuple_type
can be omitted:
uint_type calculate(tuple_type args) const {
const uint_type m = get<0>(args);
const uint_type n = get<1>(args);
if (m == 0)
return n + 1;
if (n == 0)
return calculate({m - 1, 1});
return calculate({m - 1, calculate({m, n - 1})});
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments