On Sun, Aug 01, 2021 at 07:42:07PM +0400, Abdulla Al Kathiri wrote:
> While at it, why don’t we pattern match function parameters like
> Haskel. Very elegant way for function overload.
I don't think your example is very elegant:
> case def func(int(x), [float(y), *_], int(z)) if z != 0 -> int:
> return int((x + y) / z)
>
> case def func(int(x), [float(y), *_], int(z)): -> int:
> return 0
>
> case def func(_):
> raise
That's a clear violation of DRY. The indentation is odd. And where does
the docstring go? What will `func.__annotations__` be?
It is especially awkward if you have a realistic function body rather
than a single line statement, and the syntax is just begging to be
mis-written as:
case def func(...):
body
case def func(...):
body
def func(...):
body
especially if the bodies are realistically large.
> No need to precede it with the “match” statement because we are
> pattern matching function parameters here in those cases. Also,
> annotating the parameters will be redundant.
What is so special about the case where you are matching on *exactly*
the parameters as written? That may be common, but I don't think that it
is so common that we need special syntax for it. A more general function
would pattern match on only some of the parameters, with the other
parameters used elsewhere in the function.
Of course we can always just match the other parameters with the
wild-card, but that's not very elegent.
It also promotes function annotations from an optional type hint with
no runtime semantics (other than setting `__annotations__`) to syntactic
sugar for runtime function multiple dispatch.
I think that would be far better written as a single function with the
case inside the body.
# I may have the syntax of the case statement wrong...
def func(x, alist, z): # Type-hints remain optional.
"""Docstring goes here"""
case (x, alist, z):
match (int(x), [float(y), _], 0):
return 0
match (int(x), [float(y), _], int(z)):
return int((x+y)/z)
match _:
raise SomeException
--
Steve
_______________________________________________
Python-ideas mailing list -- [email protected]
To unsubscribe send an email to [email protected]
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at
https://mail.python.org/archives/list/[email protected]/message/WGT2M6C5AKJPQY56JCXP3QHCIOF3ZHO2/
Code of Conduct: http://python.org/psf/codeofconduct/