Skip to content

Instantly share code, notes, and snippets.

@neilvallon
Created February 18, 2015 23:03
Show Gist options
  • Save neilvallon/b95abfdb975acb83a3f2 to your computer and use it in GitHub Desktop.
Save neilvallon/b95abfdb975acb83a3f2 to your computer and use it in GitHub Desktop.
PHP Streams
<?php
// Now I remember why I don't use PHP anymore.
function repeat($n) {
return function() use ($n) {
return [$n, repeat($n)];
};
}
function countFrom($n) {
return function() use ($n) {
return [$n, countFrom($n+1)];
};
}
function mapOn($s, $fn) {
return function() use ($s, $fn){
list($head, $tail) = $s();
return [$fn($head), mapOn($tail, $fn)];
};
}
function take($s, $n) {
if($n <= 0) {
return [];
}
list($head, $tail) = $s();
$arr = take($tail, $n-1);
array_unshift($arr, $head);
return $arr;
}
function combine($s1, $s2, $fn) {
return function() use ($s1, $s2, $fn) {
list($h1, $t1) = $s1();
list($h2, $t2) = $s2();
return [$fn($h1, $h2), combine($t1, $t2, $fn)];
};
}
$test1 = countFrom(1);
$test2 = mapOn($test1, function($n) {
return $n+$n;
});
$test3 = combine($test1, $test2, function($x, $y) {
return $x + $y;
});
echo "\n\tTest 1\n";
foreach(take($test1, 5) as $i) {
echo $i."\n";
}
echo "\n\tTest 2\n";
foreach(take($test2, 5) as $i) {
echo $i."\n";
}
echo "\n\tTest 3\n";
foreach(take($test3, 20) as $i) {
echo $i."\n";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment