PHP code example of spencerwi / lazylist

1. Go to this page and download the library: Download spencerwi/lazylist library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

spencerwi / lazylist example snippets


$lazyList = \Spencerwi\Lazy_list\LazyList::fromArray([1,2,3,4,5]);

$lazyList2 = new \Spencerwi\Lazy_list\LazyList(function(int $i) {
    if ($i < 10) {
        return $i;
    } else {
        return \Spencerwi\Lazy_list\LazyList::STOP_ITERATION;
    }
});
// This amounts to a LazyList containing [0,1,2,3,4,5,6,7,8,9].

$mapperWasCalled = false;
$squares = $lazyList->map(function($i): int use (&$mapperWasCalled) {
    $mapperWasCalled = true;
    return $i * $i;
});
// $mapperWasCalled is still false!

$filterFnWasCalled = false;
$oddNumbers = $lazyList->filter(function (int $i): bool use (&$filterFnWasCalled) {
    $filterFnWasCalled = true;
    return ($i % 2 === 1);
});
// $filterFnWasCalled is still false!

foreach ($squares as $square) {
    echo $square . "\n";
}
/* Output:
 * 1
 * 4
 * 9
 * 16
 * 25
 */

foreach ($squares as $index => $square) {
    echo $index . ": " . $square . "\n";
}
/* Output:
 * 0: 1
 * 1: 4
 * 2: 9
 * 3: 16
 * 4: 25
 */

$l = \Spencerwi\Lazy_list\LazyList::fromArray([1,2,3,4,5]);
$l->take(2); // returns the array [1,2]

// What happens when we take too many?
$l->take(99); // we get the whole list as an array: [1,2,3,4,5]

$l = \Spencerwi\Lazy_list\LazyList::fromArray([1,2,3,4,5]);
$->toArray(); // [1,2,3,4,5]


$l = \Spencerwi\Lazy_list\LazyList::fromArray([2,3,4]);
$sum = $l->reduce(1, function(int $previous, int $current) {
  return $previous + $current;
});
// $sum is now ((1+2)+3)+4, that is, 10. 

$l = \Spencerwi\Lazy_list\LazyList::fromArray([]);
$sum = $l->reduce(1, function(int $previous, int $current) {
  return $previous + $current;
});
// $sum is now just 1, since the list was empty