Array comprehensions shorter syntax (?)

François REMY fremycompany_pub at yahoo.fr
Sun May 29 06:45:34 PDT 2011


An alternative syntax, which I tend to prefer, is a LINQ-like syntax. Please note that LINQ don’t produce an array, but an enumerable. It means that if the result is never used, the query is never executed (and if only the first result is used, the query only executed itself to that point, and not further)
  let users = [ .... ]

  let names = (
      foreach user in users 
      select user.name 
      if user.age > 30
  );

  let newClientsSpendings = (
      foreach user in users
      let spendings = getSpendingsById(user.id)
      select spendings
      if (user.isNewClient && spendings.length!=0)
  ).merge()

But I don’t know if we really need something special (ie: a new syntax) for that kind of things. Using a short function notation + paren-free loops could do the trick pretty well :
  let newClientsSpendings = @{
      foreach user in users {
          if !user.isNewClient: continue;
          let spendings = getSpendingsById(user.id);
          if spendings.length!=0: yield spendings;
      }
  }().merge();

For your “squares” sample, that gives :
  let squares = @{ 
      foreach x in data { 
          if x<3 : yield x*x 
      }
  }();
It’s longer, but it’s aslo more extensible... and it don’t introduce anything new to ES Harmony.

Please note that your syntax has to be rejected because we can’t get intellisense working since the variable is declared after the expression.

Best regards,
François

From: Jose Antonio Perez 
Sent: Sunday, May 29, 2011 2:18 PM
To: es-discuss at mozilla.org 
Subject: Re: Array comprehensions shorter syntax (?)
2011/5/29 Dmitry A. Soshnikov <dmitry.soshnikov at gmail.com>

  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]


Basically you are proposing bring in  Haskell's syntax for comprehensions
 
  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"]


This form of located flat pattern matching is good.

Jose.  



--------------------------------------------------------------------------------
_______________________________________________
es-discuss mailing list
es-discuss at mozilla.org
https://mail.mozilla.org/listinfo/es-discuss
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/es-discuss/attachments/20110529/c90cb068/attachment.html>


More information about the es-discuss mailing list