Recursion

Bob Calco rcalco at cortechs.com
Mon Jan 1 15:54:13 EST 2001


Anyone:

I noticed the following while dabbling in Perl, Ruby and Python recently.
Take your standard factorial implementation, a la:

PYTHON
======
import sys

def factor(n):
  if n == 1:
    return 1
  else:
    return n*factor(n-1)

print factor(int(sys.argv[1]))

fact.pl
=======
sub fact {
  my($n) = shift;
  if ($n eq 1) {
    return 1;
  } else {
    return ($n * fact($n-1));
  }
}
print fact($ARGV[0]), "\n";

fact.rb
=======
def fact(n)
  if n == 1
    1
  else
    n*fact(n-1)
  end
end
print fact(ARGV[0].to_i), "\n"

The highest value for n you can run in Python is 12; after that you get
overflow error messages. In Perl, the largest value is 170 (after which you
get 1.#INF for an answer). In Ruby, you can input a value as high as 763
before you get a SystemStackError (stack level too deep) error.

Couple questions:

1. Why the vast difference between the languages? Is this apparent
limitation in Python deliberate, or the consequence of some other design
decision?

2. In the real world, does this really matter? Does Ruby have any meaningful
advantage over Python in this regard? (I understand I might get different
replies if I asked this question on the Ruby email list. I have different
questions for Ruby fans!)

I'm trying to decide which of these languages to embed in my application or
at the very least require in the user environment. I like all of them, and I
lean toward Python because it's much cleaner than Perl and more mature than
Ruby and Mark Hammond's Win32 extenstion fully supports COM on Win32, which
would make it a very useful framework for prototyping our COM objects and
developing our own test suites to exercise them when they are implemented in
C++. But I was surprised to find such a difference when testing each
language's support for recursion.

Any thoughts welcome.

Sincerely,

Bob Calco
CorTechs, Inc.
rcalco at cortechs.com





More information about the Python-list mailing list