In Mathematica, you might do this as (roughly):

rules = {
  {x_, y_, z_} :> {x, y, z},
  {x_, y_} :> {x, y, 0.0},
  x_ :> {x, 0.0, 0.0}
  }
process[Replace[obj, rules]]

Whatever you think of the particular syntax:
The ability to declare resuable rules seems good.
Thinking of replacement functionally seems good.

fwiw, Alan Isaac


On 11/17/2020 5:02 AM, Steven D'Aprano wrote:
On Tue, Nov 17, 2020 at 08:49:28AM +0100, Marco Sulla wrote:

PS: pattern matching, for a mere mortal like me, seems to be something very
exotical.

Have you ever written code that looks like this?


     if isinstance(obj, tuple) and len(obj) ==3:
         x, y, z = obj
     elif isinstance(obj, tuple) and len(obj) == 2:
         x, y = obj
         z = 0.0
     elif isinstance(obj, float):
         x = obj
         y = z = 0.0
     else:
         raise ValueError
     process(x, y, z)


That's pattern matching.

     match obj:
         case x, y, z:
             pass
         case x, y:
             z = 0.0
         case x if isinstance(x, float):
             y = z = 0.0
         case _:
             raise ValueError
     process(x, y, z)


There may be cleaner or alternative ways to write this as a match
statement, I'm still learning pattern matching idioms myself. But in a
nutshell, they simplify what would otherwise look like a long,
repetitive chain of if, isinstance, sequence unpacking, etc.


_______________________________________________
Python-Dev mailing list -- python-dev@python.org
To unsubscribe send an email to python-dev-le...@python.org
https://mail.python.org/mailman3/lists/python-dev.python.org/
Message archived at 
https://mail.python.org/archives/list/python-dev@python.org/message/JXTVH6JGCJMFSV66NQJ4EWGHWEZRMH5U/
Code of Conduct: http://python.org/psf/codeofconduct/

Reply via email to