OO in Python? ^^
Tom Anderson
twic at urchin.earth.li
Mon Dec 12 20:43:52 EST 2005
On Mon, 12 Dec 2005, Donn Cave wrote:
> In article <1h7f90l.l5s3sh1cqq9ozN%aleax at mail.comcast.net>,
> aleax at mail.comcast.net (Alex Martelli) wrote:
>
>> Tom Anderson <twic at urchin.earth.li> wrote:
>> ...
>>
>>
>>> For example, if i wrote code like this (using python syntax):
>>>
>>> def f(x):
>>> return 1 + x
>>>
>>> The compiler would think "well, he takes some value x, and he adds it to 1
>>> and 1 is an integer, and the only thing you can add to an integer is
>>> another integer, so x must be an integer; he returns whatever 1 + x works
>>> out to, and 1 and x are both integers, and adding two integers makes an
>>> integer, so the return type must be integer"
>>
>> hmmm, not exactly -- Haskell's not QUITE as strongly/rigidly typed as
>> this... you may have in mind CAML, which AFAIK in all of its variations
>> (O'CAML being the best-known one) *does* constrain + so that "the only
>> thing you can add to an integer is another integer". In Haskell, + can
>> sum any two instances of types which meet typeclass Num -- including at
>> least floats, as well as integers (you can add more types to a typeclass
>> by writing the required functions for them, too). Therefore (after
>> loading in ghci a file with
>> f x = x + 1
>> ), we can verify...:
>>
>> *Main> :type f
>> f :: (Num a) => a -> a
>
> But if you try
> f x = x + 1.0
>
> it's
> f :: (Fractional a) => a -> a
>
> I asserted something like this some time ago here, and was set straight,
> I believe by a gentleman from Chalmers. You're right that addition is
> polymorphic, but that doesn't mean that it can be performed on any two
> instances of Num.
That's what i understand. What it comes down to, i think, is that the
Standard Prelude defines an overloaded + operator:
def __add__(x: int, y: int) -> int:
<primitive operation to add two ints>
def __add__(x: float, y: float) -> float:
<primitive operation to add two floats>
def __add__(x: str, y: str) -> str:
<primitive operation to add two strings>
# etc
So that when the compiler hits the expression "x + 1", it has a finite set
of possible interpretations for '+', of which only one is legal - addition
of two integers to yield an integer. Or rather, given that "1" can be an
int or a float, it decides that x could be either, and so calls it "alpha,
where alpha is a number". Or something.
While we're on the subject of Haskell - if you think python's
syntactically significant whitespace is icky, have a look at Haskell's
'layout' - i almost wet myself in terror when i saw that!
tom
--
limited to concepts that are meta, generic, abstract and philosophical --
IEEE SUO WG
More information about the Python-list
mailing list