[erlang-questions] about tail-recursive

Peter Lemenkov <>
Wed Apr 16 11:27:54 CEST 2008


Hello All!

2008/4/16, 成立涛 <>:
> Hi everyone.
> Recently I read
> http://www.erlang.org/download/armstrong_thesis_2003.pdf.
>  In this paper 3.3.8, the author talk about tail-recursive:
>  "Firstly the non tail-recursive way:
> factorial(0) -> 1;
> factorial(N) -> N * factorial(N-1).
> "
> I see this section is non tail-recursive. In my mind, the tail-recursive is
> the better, because it do not consuming stack!

Don't be afraid of non-tail recursions. There are practical user-cases
there people claims that tail-recursion is less suitable than
non-tail-recursive realizations.

For example, if we look into ejabberd sources we may find something
like this piece of code:

=================
%tolower(S) ->
%    lists:map(fun tolower_c/1, S).

%tolower(S) ->
%    [?LOWER(Char) || Char <- S].

% Not tail-recursive but it seems works faster than variants above
tolower([C | Cs]) ->
    if
        C >= $A, C =< $Z ->
            [C + 32 | tolower(Cs)];
        true ->
            [C | tolower(Cs)]
    end;
tolower([]) ->
    [].

=================

Summarizing things - if your recursion won't take *very big*
(infinite) number of steps then you may find that non-tail recursion
will be more suitable.

-- 
With best regards!


More information about the erlang-questions mailing list