Regarding the difficulty which some people have respecting class patterns and
dictionary patterns, I would like to draw attention to a similar feature in
JavaScript, object destructuring. JavaScript does not have pattern matching but
object destructuring is closely related. Take the example of a function to
compute the distance between two points.
```
function distance(p1, p2) {
// This is an object destructuring assignment that extracts the x field of p1
into x1 and the y field of p1 into y1
const { x: x1, y: y1 } = p1;
// This is an object destructuring assignment that extracts the x field of p2
into x2 and the y field of p2 into y2
const { x: x2, y: y2 } = p2;
const dx = x2 - x1;
const dy = y2 - y1;
return Math.sqrt(dx*dx + dy*dy);
}
// An object literal is assigned to p1 here
const p1 = { x: 0, y: 0 };
// An object literal is assigned to p2 here
const p2 = { x: 1, y: 1 };
const d = distance(p1, p2);
```
Similarly to dictionary patterns in Python, object destructuring in JavaScript
places the variable names that are the targets of the assignments in the same
position where a value would be expected in an object literal. This feature has
existed in JavaScript for several years now and I would like to draw attention
to it as a counterpoint to the argument that pattern matching is not a good fit
for languages that are not statically typed. Destructuring can also be found in
Common Lisp, which is not statically typed. Pattern matching is also a core
part of Erlang, which is not statically typed..
I would also like to draw attention to the fact that object destructuring was
added to JavaScript years into it's development. I do not believe this to be a
reasonable argument against adopting pattern matching in Python.
_______________________________________________
Python-Dev mailing list -- [email protected]
To unsubscribe send an email to [email protected]
https://mail.python.org/mailman3/lists/python-dev.python.org/
Message archived at
https://mail.python.org/archives/list/[email protected]/message/6XDXHVT3ZFOK66GVU5UWYGSHJX4UF2CW/
Code of Conduct: http://python.org/psf/codeofconduct/