Search code examples
erlangtail-recursionpow

Tail recursion pow Erlang


I have a doubt, I have to do a tail recursion for this pow function:

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

I've read about it, but I do not totally get it, Can somebody explain me how to this function in tail recursion?


Solution

  • Basically in a tail recursion you need a another parameter that act as an accumulator.

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

    Hope this gives you an idea how it can be done.