尾递归 pow Erlang

Tail recursion pow Erlang

我有疑问,我必须为这个 pow 函数做一个尾递归

pow(_, 0) -> 1;
pow(N, X) when X > 0 -> N * pow(N, X - 1).

我读过它,但我不完全明白,有人能解释一下如何在尾递归中使用这个函数吗?

基本上在尾递归中你需要另一个参数作为累加器。

%% So the first step is to convert the pow function to the pow_tail function, and initialize the accumulator to the default value. 

pow(N, X) -> pow_tail(N, X, 1);

%% Defined the base case for the pow_tail, to return the accumulator

pow_tail(_, 0, ACC) -> ACC;

%% Write the pow_tail function and store the result in the accumulator

pow_tail(N, X, ACC) when X > 0 -> pow_tail(N, X-1, ACC * N);

希望这能让您了解如何完成。