Forum: Ruby tail-recursion

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
on 2007-07-14 08:16
```On Jul 14, 2007, at 1:36 AM, Trevor Squires wrote:

> sum([H|T]) -> H + sum(T);
> sum([]) -> 0.
>
> "Oh my god!  Won't that blow the stack?" - well, I *think* it's
> okay because of something called 'tail-recursion' - but like you, I
> don't know what I don't know.

For what it's worth: the function definition is "tail-recursive" and
the technique used by the compiler/interpreter to prevent stack
overflow is called "tail-recursion elimination". That is, the
compiler/interpreter transforms the recursion into an iteration
(which is relatively easy to do for tail-recursive functions).

Regards, Morton```
on 2007-07-14 15:51
```On 7/14/07, Morton Goldberg <m_goldberg@ameritech.net> wrote:
>
> On Jul 14, 2007, at 1:36 AM, Trevor Squires wrote:
>
> > sum([H|T]) -> H + sum(T);
> > sum([]) -> 0.
> >
> > "Oh my god!  Won't that blow the stack?" - well, I *think* it's
> > okay because of something called 'tail-recursion' - but like you, I
> > don't know what I don't know.

unfortunately this is not a tail recursive call. The recursive call
(sum) is
not the last call, + is. To write this tail recursively, you'd want to
use
an accumulating parameter:

sum(X) -> asum(0, X).

asum(N, [H|T]) -> asum(H + N, T);
asum(N, []) -> N.

For what it's worth: the function definition is "tail-recursive" and```
on 2007-07-14 22:50
```Hey Logan and Morton,

my thanks to both of you for the information.  Quite a lot has fallen
into place in my head because of these two emails.

Trev```
This topic is locked and can not be replied to.