From: Seth Kurtzberg Date: 2003-08-07T17:27:19+09:00 Subject: Re: Ruby Query On Thursday, August 7, 2003, at 01:05 AM, Robert Klemme wrote: > > schrieb im Newsbeitrag > news:221d8dbe.0308062037.2a5558f2@posting.google.com... >> Ruby is a nice and expressive language. Now my favourite Ruby site is >> http://whytheluckystiff.net/articles/2003/08/04/rubyOneEightOh >> >> I have a query about Ruby >> 1) Like Python can I increase the maximum depth of Ruby Interpreter >> Stack? This will help to calculate factorial(1000) recursively. >> Without increasing the recursion limit, it will not possible to >> calculate factorial(1000) recursively with Ruby 1.8 (Win 98). It is >> possible to do the same with Python. > > Hmmm... Calculating factorial recursively is really inefficient and > after > all, Ruby is not a functional language although it has some features of > them > > def fact1(n) > n == 1 ? 1 : n*fact1(n-1) > end > > def fact2(n) > f = 1 > > for i in 1..n > f *= i > end > > f > Quite true. Plus, all the modern compilers for functional languages use tail recursion optimization to convert the recursively expressed code into a loop. So even with a functional language it isn't necessary to provide a stack depth proportional to the order of recursion. > end > > require 'benchmark' > include Benchmark > > N=700 > > bm do |x| > x.report("recursive") do > for n in 1..N > fact1 n > end > end > > x.report("iterative") do > for n in 1..N > fact2 n > end > end > end > > 08:01:55 [ruby]: ruby fact.rb > user system total real > recursive 4.891000 0.015000 4.906000 ( 4.922000) > iterative 2.906000 0.000000 2.906000 ( 2.906000) > 08:02:13 [ruby]: > > Cheers > > robert > > > > > > ----------------------------------------------------------------- Seth Kurtzberg CTO ISEC Research and Network Operations Center 480-314-1540 888-879-5206 seth@isec.us -----------------------------------------------------------------