An array destructing specification choice

David Herman dherman at mozilla.com
Fri Nov 11 15:17:44 PST 2011


Late to the party, but I've brought more booze.

On Nov 5, 2011, at 2:41 PM, Brendan Eich wrote:

> We have:
> 
> 1. Should an array pattern always query 'length'?
> 
> 2. If the answer to (1) is "no", then should ... in an array pattern query 'length'?
> 
> On reflection and at this point in the thread, with your reply in mind, my prefs in order: [no, yes], [no, no]. In no case do I favor [yes]. I'm refutably matching [no, _] :-P.

I feel strongly that the appropriate semantics is [no, yes].

Here's my reasoning. Arrays are a multi-purpose data structure in JS. Sometimes they are used for fixed-size tuples, and sometimes they are used for dynamic length arrays. (Similarly, objects are used both for fixed-size records and for dynamic size dictionaries.)

When you use a fixed-length tuple in JS, you do not query the .length property. When you use a dynamic-length array, you do.

When you use a fixed-size record in JS, you do not use object enumeration. When you use a dynamic-size dictionary in JS, you do.

Destructuring is meant to provide elegant syntax for all of these use cases. The syntax of [] destructuring is for fixed-length tuples if there is no ellipsis, and for dynamic-length arrays if there is an ellipsis. That's what the ellipsis is good for; distinguishing the case where you know statically how many elements you expect from the case where you don't.

More concretely, here's the rough desugaring I expect. I'll use 〰〰 as meta-ellipsis (thanks, Unicode!). I'll just specify the special case where each element is an identifier. It's straightforward to generalize to arbitrary nested destructuring patterns and hole patterns.

A pattern of the form

    [a0, a1, 〰〰, ak]

desugars to

    a0 = %v[0];
    a1 = %v[1];
    〰〰
    ak = %v[k];

A pattern of the form

    [a0, a1, 〰〰, ak, ...r]

desugars to

    a0 = %v[0];
    a1 = %v[1];
    〰〰
    ak = %v[k];
    let %length = %v.length;
    r = [ %v[i] for i of [k+1, 〰〰, %length - 1] if (i in %v) ];

This can be generalized further to allow a fixed number of patterns *after* the ellipsis as well:

A pattern of the form

    [a0, a1, 〰〰, ak, ...r, bn, bn-1, 〰〰, b0]

desugars to

    a0 = %v[0];
    a1 = %v[1];
    〰〰
    ak = %v[k];
    let %length = %v.length;
    r = [ %v[i] for i of [k+1, 〰〰, %length - n - 2] if (i in %v) ];
    bn = %v[%length - n - 1];
    bn-1 = %v[%length - (n - 1) - 1];
    〰〰
    b0 = %v[%length - 0 - 1];

Dave



More information about the es-discuss mailing list