tail recursion : sharing a learning and a question

Amit Murthy amit.murthy@REDACTED
Sun Aug 16 15:14:50 CEST 2009


Hi,

I just learned that every iteration of the below code goes onto the stack.
The evaluation of the "catch" has something to do with it though I could
understand why.


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Bad code, Bad code, Bad code, Bad code, Bad code, Bad code,
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

do_maintenance(CacheSz, HKIntvl, Oldest) ->
    try
        receive
            Message ->
                met_util:log_info(" pid -~p recieved unexpected message[~p].
",[self(), Message])

        after HKIntvl ->
            NOldest = do_cleanup(CacheSz, Oldest, 100),
            do_maintenance(CacheSz, HKIntvl, NOldest)
        end
    catch
        error:Error ->
            met_util:log("~p do_maintenance() caught exception ->
~p",[?MODULE, Error]),
            do_maintenance(CacheSz, HKIntvl, Oldest)
    end.

%%%%%%%

The right way of course is to not trap exceptions here, remove the try-catch
and put the whole thing under a supervisor (with restart) behavior.
Which is what I have done now.

Would still like to know as to why the try-catch ends up killing tail
recursion. Can't the compiler catch this (pun intended) and optimize it for
tail recursion?

Regards,
  Amit


More information about the erlang-questions mailing list