sequence multiplied by -1

Steven D'Aprano steve-REMOVE-THIS at cybersource.com.au
Mon Sep 27 07:17:27 CEST 2010


On Sun, 26 Sep 2010 09:30:08 +0000, Seebs wrote:

>> There's nothing obscure or unintuitive about "spam"*3 = "spamspamspam",
>> and the fact that it doesn't do the same thing as int("spam")*3 is a
>> foolish argument.
> 
> The languages in which it's surprising are mostly things like perl,
> where there's a certain amount of implicit coercion going on, so it's
> ambiguous whether "3"*3 ought to mean "333" or 9.  (Except it isn't,
> because repetition is a separate operator, written "3" x 3 rather than
> "3" * 3...)  People coming from that kind of background may be expecting
> * to stay an arithmetic operator, rather than having it change form when
> applied to non-arithmetic objects.

And people with no programming background at all will be surprised that * 
and x aren't two different symbols for the same operation.



> I'm not sure either way.  I think on the whole, I like the notion of a
> repetition operator which is distinct from multiplication, but I also
> definitely prefer the lack of implicit coercion, and without implicit
> coercion, there's a lot less underlying ambiguity to worry about.
> 
> From the top, I guess my analysis is:
> 
> * It seems clear that, given two sequences x and y, "x + y" ought to
>   be the concatenation of these sequences.
> * Thus, "x + x" should be x concatenated to itself. * Idiomatically, it
> is not unreasonable to assert that "x * 2" and "x + x"
>   could be the same value.
> * It thus makes some sense for <sequence> * <number> to indicate
>   repetition of the sequence.
> * Since a string is a kind of a sequence, it also makes sense for
>   <string> * <number> to indicate repetition.

My analysis as well, except that I see repetition (repeated concatenation/
addition) as more fundamental than multiplication. Think about being back 
in primary school, where you learn to do this:


 21
 21
+21
----
 63


before you learned this:

 21
 x3
----
 63




> So I think I'm pretty much convinced that Python's behavior makes sense,
> but it makes sense only because I'm going into this expecting operators
> to be defined by types, so I don't expect every '*' to mean
> 'multiplication'.

Perhaps you should say "real-valued multiplication" rather than just 
multiplication, because of course matrix multiplication A*B behaves quite 
differently from integer multiplication a*b as well.



> Helps, perhaps, that I got exposed to group theory early enough to be
> used to redefining + and * to be any two operations which have
> interesting properties*.
> 
> -s
> [*] What's purple and commutes?  An abelian grape.


Heh :)



-- 
Steven



More information about the Python-list mailing list