Ruby tailcall optimizes?

C

cnb

Hmm this was a nice surprise. it seems Ruby does tailcall-
optimization? One up for Ruby on Python.

Is there a way to have optional arguments in Ruby? Then I could make
it one function instead of wrapping them.

irb(main):011:0> fact(12000)
fact(12000)
1201858406751094813215537862229...
irb(main):012:0> fac(12000)
fac(12000)
SystemStackError: stack level too deep
from c:/ruby/Progs/blandat/learn.rb:34:in `fac'
from c:/ruby/Progs/blandat/learn.rb:34:in `fac'
from (irb):12
irb(main):013:0>


def fact(n)
def f(n, acc)
if n > 0
then f(n-1, n*acc)
else acc
end
end
f(n, 1)
end

def fac(n)
if n > 0
then n * fac(n-1)
else 1
end
end
 
C

cnb

wow this was nice and elegant and i can even call it with fac 5 withou
parenthesis. .

def fac(n, acc=1)
if n > 0
then fac(n-1, n*acc)
else acc
end
end
 
R

Robert Klemme

2008/9/8 cnb said:
Hmm this was a nice surprise. it seems Ruby does tailcall-
optimization?

It doesn't.

13:51:03 ~$ ruby -e 'def t(a)a>0?t(a-1):a;end;t 1_000_000'
-e:1:in `t': stack level too deep (SystemStackError)
from -e:1:in `t'
from -e:1
13:51:39 ~$ ruby19 -e 'def t(a)a>0?t(a-1):a;end;t 1_000_000'
-e:1:in `t': stack level too deep (SystemStackError)
from -e:1:in `t'
from -e:1:in `t'
from -e:1:in `t'
from -e:1:in `t'
from -e:1:in `t'
from -e:1:in `t'
from -e:1:in `t'
from -e:1:in `t'
... 7264 levels...
from -e:1:in `t'
from -e:1:in `t'
from -e:1:in `t'
from -e:1:in ` said:
Is there a way to have optional arguments in Ruby?

Did you read the documentation?

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

No members online now.

Forum statistics

Threads
473,770
Messages
2,569,586
Members
45,084
Latest member
HansGeorgi

Latest Threads

Top