Array comprehensions shorter syntax (?)

Dmitry A. Soshnikov dmitry.soshnikov at gmail.com
Sun May 29 02:38:13 PDT 2011


Hi,

Don't get this proposal as a bikesheding, just an idea in case if arrow 
functions will win the block-functions.

What about to make a sugar for Array comprehensions based also on arrow 
syntax? The same as in Erlang:

let data = [1, 2, 3, 4, 5];

let squares = [x * x | x <- data, x > 3]; // [16, 25]

Which basically is the:

let squares = [x * x for (x in values(data)) if (x > 3)]; // [16, 25]

A semantic (important) difference is that in the later case we use 
values(...) generator function to get the values. In case of shorter 
syntax, the array is assumed to be traversed over values by default.

P.S.:

1. This syntactic construct is directly reflects the sets builder from 
set theory (http://en.wikipedia.org/wiki/Set-builder_notation), which 
again directly reflects arrays comprehensions concept:

S = { 2 · x | x  N }

2. Erlang actually uses two pipes, in this proposal I think one pipe is 
enough (like in Haskel IIRC):

Erlang: Squares = [X * X || X <- Data, X > 3];

3. Of course it's assumed that we can destructure elements in such array 
comprehensions:

let users = [
   {name: "Alex", age: 31},
   {name: "John", age: 25},
   {name: "Mark", age: 33}
];

let names = [name | {name, age} <- users, age > 30]; // ["Alex", "Mark"]

3.1. ...which can lead to real pattern-matching Dave's proposal to be 
included ;) "switch-on-steroids" is very powerful thing.

Dmitry.


More information about the es-discuss mailing list