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).
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
