<?php
function powerSet(Iterator $iterator){
if(!$iterator->valid()){
return yield new EmptyIterator();
}
$one = $iterator->current();
$rest = new NoRewindIterator($iterator);
$rest->next();
foreach(powerSet($rest) as $set){
$set = iterator_to_array($set);
yield new ArrayIterator($set);
// why does this work
yield (function($set, $one){
yield from array_merge($set, [$one]);
})($set, $one);
// but this doesn't?
// yield (function($set, $one){
// yield from $set;
// yield $one;
// })($set, $one);
}
}
function baz(){
yield 1;
yield 2;
yield 3;
yield 4;
}
$sets = powerSet(baz());
foreach($sets as $i => $set){
echo $i+1 . " {";
$arr = iterator_to_array($set);
echo implode(", ", $arr);
echo "}\n";
}
- Output for 7.0.0 - 7.0.20, 7.1.0 - 7.1.20, 7.2.0 - 7.2.33, 7.3.16 - 7.3.33, 7.4.0 - 7.4.33, 8.0.0 - 8.0.30, 8.1.0 - 8.1.28, 8.2.0 - 8.2.18, 8.3.0 - 8.3.4, 8.3.6
- 1 {}
2 {1}
3 {2}
4 {2, 1}
5 {3}
6 {3, 1}
7 {3, 2}
8 {3, 2, 1}
9 {4}
10 {4, 1}
11 {4, 2}
12 {4, 2, 1}
13 {4, 3}
14 {4, 3, 1}
15 {4, 3, 2}
16 {4, 3, 2, 1}
- Output for 8.3.5
- Warning: PHP Startup: Unable to load dynamic library 'sodium.so' (tried: /usr/lib/php/8.3.5/modules/sodium.so (libsodium.so.23: cannot open shared object file: No such file or directory), /usr/lib/php/8.3.5/modules/sodium.so.so (/usr/lib/php/8.3.5/modules/sodium.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0
1 {}
2 {1}
3 {2}
4 {2, 1}
5 {3}
6 {3, 1}
7 {3, 2}
8 {3, 2, 1}
9 {4}
10 {4, 1}
11 {4, 2}
12 {4, 2, 1}
13 {4, 3}
14 {4, 3, 1}
15 {4, 3, 2}
16 {4, 3, 2, 1}
- Output for 5.5.0 - 5.5.35, 5.6.6 - 5.6.28
- Parse error: syntax error, unexpected 'new' (T_NEW) in /in/tBY4O on line 5
Process exited with code 255.
preferences:
216.6 ms | 402 KiB | 205 Q