tc39 / proposal-pattern-matching

Pattern matching syntax for ECMAScript
https://tc39.es/proposal-pattern-matching/
MIT License
5.5k stars 89 forks source link

Pattern-matching `#record{}` & `#tuple[]` #289

Closed kael closed 1 year ago

kael commented 1 year ago

In erlang it's possible to pattern-match #record{} and tuple{}:

% Record pattern-matching
find_phone([#person{name=Name, phone=Phone} | _], Name) ->
    {found,  Phone};
find_phone([_| T], Name) ->
    find_phone(T, Name);
find_phone([], Name) ->
    not_found.
% Tuple pattern-matching
f({connect,_,To,_,_} = Signal, To) ->
    ...;
f(Signal, To) ->
    ignore.

Is there any plan to integrate pattern-matching with the #record{} and #tuple[] proposal ?

ljharb commented 1 year ago

Yes, absolutely. Whichever proposal advanced second would be obligated to support the other one.

theScottyJam commented 1 year ago

Patter-matching with records/tuples should be auto-supported (unless one of these two proposals have a radical shift in their direction). I'll just focus on object and records, but the same applies for arrays and tuples.

(I'm using "auto-supported" loosely here. Of course, the spec for pattern-matching will need to address records, and whoever is the later proposal would need to contain the modifications to do so).

Semantically, from what I understand, there's not supposed to be a difference between how you use an object and how you use a record, unless you're specifically trying to modify an object. So, to access the y property on an x object, you do x.y, and with records, you also do x.y. This allows for polymorphic code, where you can easily write functions that work either with objects or records. This principle is explained in their readme over here (and maybe elsewhere too, I haven't looked at it for a bit).

This means, when it comes to pattern matching, the syntax to match an object should be exactly the same as the syntax to match a record. i.e. both should use { ... } syntax. Creating special syntax to pattern-match a record would just make the code non-polymorphic, going against one of the core principles of the record/tuple proposal.

I'd assume that destructuring will work the same - both objects and records would use { ... } syntax for it.

ljharb commented 1 year ago

Yep, exactly that.