[erlang-questions] Idiomatic Erlang, style/performance question
Thu Jun 19 15:43:58 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
It can be slower. The advantage is that the stack doesn't
grow, so you can use the function on lists of any size without
risking running out of memory. You don't always need that.
>>> 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
It's a call to a different function (ipower), so it's not
recursive at all. Had it been a call to itself, your remark would
be quite correct.
>>> ipower(0, _, R) -> R;
>>> ipower(N, P, R) -> ipower(N-1, P, R*P).
ipower is tail-recursive.
More information about the erlang-questions