tc39 / proposal-extractors

Extractors for ECMAScript
http://tc39.es/proposal-extractors/
MIT License
200 stars 3 forks source link

Semantics of match failure #1

Closed littledan closed 1 year ago

littledan commented 1 year ago

The Symbol.match protocol sometimes succeeds and sometimes fails. If it returns failure, what would the semantics be? (I'd suggest: the same kind of exception is thrown as if a match expression falls through and there's no default case.)

rbuckton commented 1 year ago

This is mentioned in https://github.com/rbuckton/proposal-extractors#proposed-solution: in a binding or assignment pattern, failure would throw a TypeError.

This is not only consistent with languages like Scala, but with how destructuring works in ECMAScript today:

const { x, y } = null; // throws TypeError
const [x, y] = {}; // throws TypeError

Extractors are always destructured as either an object or an array. It would be somewhat like a failing match resulting in null when the match fails, i.e.:

const Option.Some(value) = opt;

// is roughly like
const [value] = Option.Some[Symbol.matcher](opt).value;

Except we would throw a more descriptive error than TypeError: null is not iterable.

In pattern matching, a failing match would result in choosing a different alternative or trying the next match leg.

littledan commented 1 year ago

Ah, sorry for the redundant question from me reading too fast! I'm happy with these semantics.