Lui*_*nda 1 erlang tail-recursion pow
我有一个疑问,我必须为这个pow函数做一个尾递归:
pow(_, 0) -> 1;
pow(N, X) when X > 0 -> N * pow(N, X - 1).
Run Code Online (Sandbox Code Playgroud)
我已经读过它了,但是我还没有完全理解它,有人可以解释我如何在尾递归中使用这个函数吗?
基本上在尾递归中,您需要另一个充当累加器的参数.
%% 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(N, X-1, ACC * N);
Run Code Online (Sandbox Code Playgroud)
希望这能让您了解如何做到这一点.