xp-framework / compiler

Compiles future PHP to today's PHP.
19 stars 0 forks source link

Implement list comprehensions #59

Closed thekid closed 5 years ago

thekid commented 5 years ago

Examples

for

// This...
$list= [];
for ($i= 0; $i < 10; $i++) {
  $list[]= $i;
}

// ...becomes:
$list= [for ($i= 0; $i < 10; $i++) yield $i];

if

// This...
$actions= [new Add()];
if ($admin) $actions[]= new Delete();
$actions[]= new Delete();

// ...or this:
$actions= array_filter([new Add(), $admin ? new Delete() : null, new Edit()];

// ...becomes:
$actions= [new Add(), if ($admin) yield new Delete(), new Edit()];

foreach

// This...
$flipped= [];
foreach ($input as $key => $val) {
  $flipped[$val]= $key;
}

// ...becomes
$flipped= [foreach ($input as $key => $val) yield $val => $key];

See https://docs.python.org/3/reference/expressions.html and https://dart.dev/guides/language/language-tour#collection-operators

/cc @mikey179

thekid commented 5 years ago

There's a PHP RFC for this with slightly different syntax:

$gen = [for $list as $x if $x % 2 yield $x*2];

https://wiki.php.net/rfc/comprehensions

thekid commented 5 years ago

Can be implemented as external plugin once #66 is merged