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:infac’
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
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 `’
Is there a way to have optional arguments in Ruby?
Did you read the documentation?
robert
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.