nicofff/lazy-iter

受Rust启发的惰性数组函数链

0.0.2 2020-08-01 23:13 UTC

This package is auto-updated.

Last update: 2024-09-29 05:42:48 UTC


README

受Rust启发的惰性数组函数链

设计目标

  1. 惰性计算(即惰性评估)
  2. 具有与Rust的Iterator类似的接口
  3. 利用静态代码分析器来验证类型正确性

安装

composer require nicofff/lazy-iter

PHP 7.4 必须支持

示例

<?php
require_once __DIR__ . '/vendor/autoload.php';
use LazyIter\LazyIter;
use LazyIter\Helpers\Generators\Range;

// Calculate the sum of all the squared numbers below a million
$sum_squares_under_a_million = 
    (new LazyIter(Range::rangeFrom(1))) // Start with an iterator over all positive numbers
	->map(fn($n) => pow($n,2) ) // Square each one of them
	->take_while(fn($n) => $n < 1_000_000 ) // Stop once we reach a million
	->sum(); // sum them

echo $sum_squares_under_a_million;

项目状态

实现的方法(基于 Rust的Iterator特性

  • all
  • any
  • chain
  • collect
  • count
  • cycle
  • filter
  • fold
  • for_each
  • last
  • map
  • nth
  • skip
  • sum
  • take
  • take_while

类型强制

目前使用PHPStan进行类型验证。查看type_tests以获取每个方法缓存的列表

示例

LazyIter::fromArray([2,4,6,8])
->for_each(function(string $n): void{
	echo $n;
});

引发

Parameter #1 $callable of method                                      
         LazyIter\LazyIter<int,int>::for_each() expects callable(int): mixed,  
         Closure(string): void given. 

接受支持Phan和Psalm的贡献