Syntax for end recursion

R

Robert.Koepferl

Hi,
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"
Not that I need it, I'm just interested.
 
R

Robert Klemme

Hi,
does ruby have a syntax or some way to tell it to use end recursion.
No.

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"
Not that I need it, I'm just interested.

From my experience you're better off in Ruby if you omit recursion because
the stack is not really deep:

def foo(n); puts n; foo(n+1); end

foo(1) =>
....

15381
15382
15383
15384
SystemStackError: stack level too deep
from (irb):1:in `foo'
from (irb):1:in `foo'
from (irb):1:in `foo'
from (irb):1:in `foo'
from (irb):1:in `foo'
from (irb):1:in `foo'
from (irb):1:in `foo'
from (irb):1:in `foo'
from (irb):1:in `foo'
from (irb):1:in `foo'
from (irb):1:in `foo'
from (irb):1:in `foo'
from (irb):1:in `foo'
from (irb):1:in `foo'
from (irb):1:in `foo'
from (irb):1:in `foo'
.... 15354 levels...
from (irb):1:in `foo'
from (irb):1:in `foo'
from (irb):1:in `foo'
from (irb):1:in `foo'
from (irb):1:in `foo'
from (irb):1:in `foo'
from (irb):1:in `foo'
from (irb):1:in `foo'
from (irb):1:in `foo'
from (irb):1:in `foo'
from (irb):1:in `foo'
from (irb):1:in `foo'
from (irb):1:in `foo'
from (irb):1:in `foo'
from (irb):1:in `foo'
from (irb):2irb(main):003:0>

This isn't sufficient if you want to create heavily numeric applications.

robert
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,138
Messages
2,570,804
Members
47,349
Latest member
jojonoy597

Latest Threads

Top