# Antwort: Re: Syntax for end recursion

**URL:** <https://rubytalk.org/t/antwort-re-syntax-for-end-recursion/8549>\
**Category:** ruby-talk\
**Created:** [16 October 2003 15:39 UTC](https://rubytalk.org/t/antwort-re-syntax-for-end-recursion/8549 "2003-10-16T15:39:44Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![Robert\_Koepferl](https://avatars.discourse-cdn.com/v4/letter/r/b2d939/32.png) [@Robert\_Koepferl](https://rubytalk.org/u/Robert_Koepferl)\
**Post date:** [16 October 2003 15:39 UTC](https://rubytalk.org/t/antwort-re-syntax-for-end-recursion/8549/1 "2003-10-16T15:39:44Z")

</div>

Yes, tail means the same as my end.  
You’re right. I oversaw the multiply, wich gets of course the last  
instruction.

thx

> does ruby have a syntax or some way to tell it to use end recursion.  
> I tried to write a recoursive factorial function (to test BigNum).  
> However  
> the stack is limited (of course).
> 
> ```
> def fak(z)
> return 1 if z<=1;
> z* fak(z-1) if z>1;
> end
> 
> ```
> 
> in some languages it’s possible “to return first and then invoke the last  
> instruction”

Maybe I’m wrong, but isn’t that impossible in this case since the last  
instruction is the multiply and the recursive call is the one-to-last  
instruction? You can make it tail recursive (is that the same as end  
recursive?) by using an accumulating parameter:

def fac(z)  
fac\_acc(1, z)  
end

def fac\_acc(n, z)  
return n if z \<= 1  
fac\_acc(n \* z, z - 1)  
end

This is tail recursive, and you can do the tail recursion optimization  
since the recursive call is the last ‘instruction’ in the method. But  
apparently ruby doesn’t do the optimization and still runs out of stack  
space. Don’t know the answer to that I’m afraid. Note that many languages  
like Prolog, Scheme, Lisp, Haskell, … can do the tail recursion  
optimization without user directives. Even .NET supports it. There it is  
the compiler that finds out, but technically that’s easy if the programmer  
makes his recursive functions tail recursive.

Peter
