"Structural pattern matching" for Python, part 2
"Structural pattern matching" for Python, part 2
Posted Sep 8, 2020 17:39 UTC (Tue) by johill (subscriber, #25196)In reply to: "Structural pattern matching" for Python, part 2 by ecree
Parent article: "Structural pattern matching" for Python, part 2
I also just realized that I sort of sketched the basics of "algebraic matching", where the original PEP completely bypassed that issue and (x, x) doesn't even do what seems obvious? Or am I reading that wrong?
Of course some more complex expressions would be ... hard. Probably not impossible, but hard. You'd have to make the CapturedVar() be able to track all kinds of things, if you wanted to be able to write
...
if m := matches((capture.x(int), capture.x(int)**2)):
print("Integer point on the parabola at %d" % m.x)
...
It still seems possible, but ... tricky to say the least. Effectively, "CapturedVar" would have to be able to be operated on in a symbolic fashion, always returning a new CapturedVar object that encapsulates the expression, and can later evaluate it. So given an instance
x_square := CapturedVar('x') ** 2
you'd have to be able to calculate x_square(7)so you can compare to
capture.x(7).
But you can see the ambiguity here! I previously allowed
capture.x(int)to indicate you wanted a specific type ...
This would be better if the types were to rely on type annotations, but I don't think you can do that in this fashion.
I suppose you could detect if the argument was a type or an instance or something? But tricky to differentiate ...
Oh, I have an idea. The
x_square(7)calculation is purely internal, so we can do it as
x_square(value=y)(say the signature is "__call__(self, type=None, value=None)" so you can differentiate more easily. The value passing syntax is only needed internally to evaluate when you have a given thing in hand.
Well, basically ... it get complex, but I haven't hit anything I couldn't do.
Now I'm tempted to actually implement it :-)
