Python is DOOMED! Again!

Steven D'Aprano steve+comp.lang.python at pearwood.info
Sun Feb 8 02:55:43 EST 2015


Chris Angelico wrote:

> On Sun, Feb 8, 2015 at 11:45 AM, Albert van der Horst
> <albert at spenarnc.xs4all.nl> wrote:
>> def square(x): x**2
>> but
>> square = x->x**2
>>
>> or
>>
>> mult  = x,y ->
>>    result = 0
>>    for i in range(x):
>>       result +=y
>>    return result
>>
>> doing away with the ternary operator def
>>
>> def .. ( .. ) : ..
>>
>> replacing it by two binary operators, one of them (=) being thoroughly
>> familiar.
> 
> Thing is, "def" isn't just assignment. It also takes the name and
> stores it in the object. There's a distinct and visible difference
> between:
> 
> def square(x): return x**2
> 
> and
> 
> def func(x): return x**2
> square = func
> 
> So if you were to use your alternate syntax everywhere, you'd
> basically be throwing away all the benefits of def over lambda.


If this were syntax, then the compiler could just as easily set the function
name from -> as from def. Lambda has the limitations that it has because it
is an expression, not because of magical "def" properties.

I think it is a total waste of good syntax to limit a hypothetical ->
operator to a mere replacement for "def". It would be much more interesting
for pattern-matching, rather like Haskell:

fact 0 = 1
fact n = n*fact(n-1)


That is more or less equivalent to pseudocode:

def fact(arg):
    if arg == 0: return 1
    if arg matches n: return n*fact(n-1)

    
What does it mean to "match n"? Haskell can infer that n must be an integer.
(It might even be able to infer that n must be a *positive* integer. I'd
test it myself except I'm lazy.) So if it receives an integer argument
which isn't 0, it will match n.

Because indentation in Python is significant, we could drop the repeated use
of the function name by indenting the individual patterns, and use type
annotations to specify different types:

fact 0 -> 1
    n:int -> n*fact(n-1)
    x:float -> math.gamma(x-1)


As I said, this is not a thought-out proposal, just some ideal musings, but
it seems a crying shame to waste a potential pattern match operator for a
mere abbreviation to "def".



-- 
Steven




More information about the Python-list mailing list