[erlang-questions] Idiomatic Erlang, style/performance question

David King <>
Thu Jun 19 00:09:57 CEST 2008


>> Hmm while writing I got a thought. Is the last function
>> tail-recursive? I have only heard that term but never used it.
>> Is tail-recursion faster or uses less memory, what is the
>> advantage/disadvantage?
>> power(N, P) when is_integer(N), N >= 0 ->
>>        ipower(N, P, 1);
>>    power(N, P) when is_integer(N), N < 0 ->
>>        1/ipower(-N, P, 1).

This one is not tail-recursive (the latter clause most perform a  
division before turning

>>
>>
>>    ipower(0, _, R) -> R;
>>    ipower(N, P, R) -> ipower(N-1, P, R*P).
>>
>>
> Yup, this looks tail recursive, because the recursive call to ipower  
> is
> the last thing in the function.
>
> TR functions can run in constant stack space; to write a server you  
> must
> use tail recursion.
>
> -- 
> |Deryk Barker, Computer Science Dept. | Music does not have to be  
> understood|
> |Camosun College, Victoria, BC, Canada| It has to be listened  
> to.           |
> |email:           
> |                                     |
> |phone: +1 250 370 4452               |         Hermann  
> Scherchen.          |
>
>
> _______________________________________________
> erlang-questions mailing list
> 
> http://www.erlang.org/mailman/listinfo/erlang-questions




More information about the erlang-questions mailing list