Skip to content

Instantly share code, notes, and snippets.

@tanishiking
Last active August 29, 2015 14:26
Show Gist options
  • Save tanishiking/515f4fa3c03c466ccf4a to your computer and use it in GitHub Desktop.
Save tanishiking/515f4fa3c03c466ccf4a to your computer and use it in GitHub Desktop.
<?php
function take($num, $iterable) {
$i = 0;
foreach($iterable as $key => $val) {
if($i >= $num) {
break;
} else{
$i++;
yield $key => $val;
}
}
}
function map(callable $function, $iterable) {
foreach($iterable as $key => $val) {
yield $key => $function($val);
}
}
function filter(callable $predicate, $iterable) {
foreach($iterable as $key => $val) {
if($predicate($val)) {
yield $key => $val;
}
}
}
$iter = take(6, fib_gen());
foreach($iter as $v) {
var_dump($v);
}
/**
* int(0)
* int(1)
* int(1)
* int(2)
* int(3)
* int(5)
*/
$double = function($i) {
return $i * 2;
};
$isOdd = function($n) {
return $n % 2 !== 0;
};
$iter = map($double, filter($isOdd, take(10, fib_gen())));
foreach($iter as $v) {
var_dump($v);
}
/**
* int(2)
* int(2)
* int(6)
* int(10)
* int(26)
* int(42)
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment