Skip to content

Instantly share code, notes, and snippets.

@beerendlauwers
Created January 13, 2015 11:48
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 beerendlauwers/9f0492f90a0fadb361e5 to your computer and use it in GitHub Desktop.
Save beerendlauwers/9f0492f90a0fadb361e5 to your computer and use it in GitHub Desktop.
Newtypes for richer type hinting of Matt Pryor's Lazy\Sequence library
<?php
// Some newtypes that allow for richer type hinting in Matt Pryor's Lazy\Sequence library. https://bitbucket.org/mkjpryor/lazy-sequence/wiki/Home
interface ArrayInterface extends Traversable {
}
class Finite implements IteratorAggregate, ArrayInterface {
private $generator;
public function __construct( Traversable $g ) {
$this->generator = $g;
}
public function getIterator() {
return $this->generator;
}
}
class Infinite implements IteratorAggregate, ArrayInterface {
private $generator;
public function __construct( Traversable $g ) {
$this->generator = $g;
}
public function getIterator() {
return $this->generator;
}
}
function repeatx($x) {
$f = function($x) {
for(;;) {
yield $x;
}
};
return new Infinite( $f($x) );
}
function takex($seq, $n) {
$f = function($seq,$n) {
$i = 0;
return takeWhile($seq, function() use($n, &$i){
$i++;
return $i <= $n;
});
};
return new Finite($f($seq,$n));
}
function takeWhile($seq, callable $predicate) {
$f = function($seq, callable $predicate) {
foreach( $seq as $item ) {
if( !call_user_func($predicate, $item) ) {
break;
}
yield $item;
}
};
return new Infinite($f($seq,$predicate));
}
function reduce(Finite $seq, callable $reducer, $initial) {
$accum = $initial;
foreach( $seq as $item ) {
$accum = call_user_func($reducer, $accum, $item);
}
return $accum;
}
// Some tests
foreach( takex(repeatx(1),5) as $d) {
var_dump($d);
}
// Works
var_dump(reduce(takex(repeatx(1),5),function($x,$y) { return $x+$y; },''));
// Type error!
var_dump(reduce(repeatx(1),function($x,$y) { return $x+$y; },''));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment