Erlang / Erlang Advanced Interview questions
How do you write a properly tail-recursive accumulator-based function?
The standard technique is to carry the running result forward as an extra argument (an accumulator), so each recursive call is the last thing that happens — there's no pending arithmetic or list-building left to do after the call returns.
%% Not tail-recursive: work (H + Rest) happens after sum/1 returns sum([]) -> 0; sum([H|T]) -> H + sum(T). %% Tail-recursive: accumulator carries the running total sum(List) -> sum(List, 0). sum([], Acc) -> Acc; sum([H|T], Acc) -> sum(T, Acc + H). %% recursive call is the last operation
A common gotcha is doing this with lists via [H|Acc] to "reverse-build" a result: it's properly
tail-recursive, but produces the list in reverse order, so you finish with a single
lists:reverse/1 call at the end rather than trying to build the list in order (which typically
isn't tail-recursive when appending to the end at each step).
More Related questions...