Python from Wise Guy's Viewpoint

Marcin 'Qrczak' Kowalczyk qrczak at knm.org.pl
Tue Oct 28 04:55:58 EST 2003


On Tue, 28 Oct 2003 02:46:54 +0100, Pascal Costanza wrote:

> Sorry, I don't get this. Why should it be more dangerous with dynamic 
> typing? Common Lisp definitely gets this right, and most probably some 
> other dynamically typed languages.

Common Lisp, Scheme and Perl get it right: the result of / on integers
is a rational or floating point number, and integer division is spelled
differently.

Python and Ruby get it wrong: the result is an integer (truncated
division), very different from the result of / on the same numbers
represented in a different type.

If a statically typed language get's this "wrong", it doesn't hurt, except
newbies which write 1/n. For example consider this:

   double foo(double *a, int len)
   {
      ... Some computation involving a[i]/a[j] which is supposed
      ... to produce a true real quotient.
   }

You make some array of doubles, set a[i] = exp(i) (a double) and it works.
Then you set a[i] = 2*i (an integer) and it still works, because the
integer has been converted to double during assignment. An integer can be
used in place of a double with the same value.

Now in a dynamically typed language the analogous code would set some
array elements to integers without conversion. If division on them means
a different thing, an integer can no longer be used in place of a floating
point number with the same value. And division is the only operation whith
breaks this.

Dynamically typed languages shouldn't use / for both real and truncating
division. For statically typed languages it's only a matter of taste (I
prefer to use different symbols), but for dynamically typed languages it's
important to prevent bugs.

-- 
   __("<         Marcin Kowalczyk
   \__/       qrczak at knm.org.pl
    ^^     http://qrnik.knm.org.pl/~qrczak/





More information about the Python-list mailing list