2017-11-13 10 views
1

私は疑問を持って、私はこの捕虜機能に末尾再帰をしなければならない。末尾再帰POWアーラン

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

私はそれについて読んだが、私は完全にそれを得ることはありません、誰か缶尾の再帰におけるこの関数の使い方を教えてください。

答えて

7

基本的に、テール再帰では、アキュムレータとして動作する別のパラメータが必要です。

%% 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); 

これはどのように行うことができるかを示します。

+0

ありがとう、私は本当に末尾再帰関数を行う方法を理解しています。 –

関連する問題