Thu, 05 Apr 2007

* Kragen Javier Sitaker <kragen at pobox.com> [2007-04-02 09:40]:
> However, there are several cases where Python's data structures
> are fairly strict in ways that help catch bugs, but which are
> irritating coming from Perl or JavaScript, and which make your
> programs bigger:
> - There's no implicit conversion between strings and numbers, or
>   actually strings and anything.

Note there is interplay here with another issue. Javascript does
two things: overloaded operators *and* implicit conversions. That
easily leads to surprises. F.ex., consider the following:

    function add( a, b ) { return a + b }

This will return a number if both operands are numbers, but a
string if either is a string. If you want to write a reliably
numeric addition, you have to go through contortions:

    function add( a, b ) { return parseInt( a ) + parseInt( b ) }

If you want to reliably “add” (ie. concatenate) strings, it’s not
quite so bad:

    function concat( a, b ) { return "" + a + b }

I consider this botched. Many programmers are not even aware of
these subtleties and those who are will frequently skip the
tedious work of making the code robust.

Python avoids this trap by outlawing implicit conversions.

Perl goes in the other direction: it does implicit conversion,
but not overloaded operators. String concatenation is spelled
`.` whereas numeric addition is spelled `+`. Operands are
implicitly coerced into the type expected by the operator, but
the type of operation is always explicit.

Compare with Python; consider the following function:

    def add( a, b ): return a + b

You can call this either with two numbers, in which case you get
a number back out, or with two strings, which gives you back a
string. You just can’t mix strings and numbers like you can in
Javascript.

So really, Javascript and Perl share one characteristic, but if
you look at the trio from another angle, Javascript and Python
are alike and Perl is distinct.

In fact, Perl 6 goes even further: in Perl 5, the bitwise
operators are overloaded and exhibit different behaviour when
operating on strings vs numbers; as well, the `x` operator is
either string-repeat or list-repeat depending on whether the left
operand is surrounded by parentheses or not. Perl 6 splits all of
these out to separate operators that have exactly one meaning.

Regards,
-- 
Aristotle Pagaltzis // <http://plasmasturm.org/>