Skip to content

Instantly share code, notes, and snippets.

@do-aki
Created September 3, 2013 11:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save do-aki/6422734 to your computer and use it in GitHub Desktop.
Save do-aki/6422734 to your computer and use it in GitHub Desktop.
trait と generator の練習。
<?php
trait GeneratorAction {
private $_g;
public function initializeGenerator($g) {
$this->_g = $g;
}
public function getGenerator() {
return $this->_g;
}
public function toArray() {
$ret = array();
foreach ($this->getGenerator() as $n) {
$ret[] = $n;
}
return $ret;
}
public function take($take) {
$this->_g = self::_take($this->_g, $take);
return $this;
}
public function offset($offset) {
$this->_g = self::_offset($this->_g, $offset);
return $this;
}
public function select($pred) {
$this->_g = self::_filter($this->_g, $pred);
return $this;
}
public function reject($pred) {
$reverse = static function ($n) use ($pred) { return !$pred; };
$this->_g = self::_filter($this->_g, $reverse);
return $this;
}
public function apply($func) {
$this->_g = self::_apply($this->_g, $func);
return $this;
}
private static function _take($g, $take) {
foreach($g as $n) {
if (--$take < 0) {
return;
}
yield $n;
}
}
private static function _offset($g, $offset) {
foreach($g as $n) {
if (0 < $offset--) {
continue;
}
yield $n;
}
}
private static function _filter($g, $pred) {
foreach ($g as $n) {
if ($pred($n)) {
yield $n;
}
}
}
private static function _apply($g, $func) {
foreach ($g as $n) {
yield $func($n);
}
}
}
class InfinityArray {
use GeneratorAction;
public function __construct() {
$this->initializeGenerator($this->infinity());
}
private function infinity() {
$i = 0;
while(++$i) {
yield $i;
}
}
}
print_r(
(new InfinityArray())
->offset(10)
->select(function($i){return $i%2==0;})
->take(5)
->toArray()
);
/*
Array
(
[0] => 12
[1] => 14
[2] => 16
[3] => 18
[4] => 20
)
*/
print_r(
(new InfinityArray())
->take(5)
->apply(function($n) { return $n * 2; })
->toArray()
);
/*
Array
(
[0] => 2
[1] => 4
[2] => 6
[3] => 8
[4] => 10
)
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment