尾部递归pow Erlang
我有一个疑问,我必须为这个pow函数做一个尾部递归:尾部递归pow Erlang,erlang,tail-recursion,pow,Erlang,Tail Recursion,Pow,我有一个疑问,我必须为这个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 initiali
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);
希望这能给你一个方法。谢谢,我真的理解了如何做尾部递归函数。