斐波那契数列,使用PHP迭代器、生成器实现(yield)

斐波那契数列其数学定义为:F0=1,F1=1,Fn=F(n-1)+F(n-2)(n>=2)

普通解法for循环


PHP 迭代器

PHP 迭代器 继承Iterator 接口,实现5个方法即可
而生成器循环返回的是中间值

class Fb implements Iterator
{
    public function __construct($len)
    {
        $this->len = $len;
    }
    private $len = 0;
    private $pre = 1;
    private $curr = 1;
    private $count = 0;

    public function current()
    {
        return $this->curr;
    }

    public function next()
    {
        $tmp = $this->curr;
        $this->curr += $this->pre;
        $this->pre = $tmp;
        $this->count++;
    }

    public function key()
    {
//        return $this->key;
    }

    public function valid()
    {
        return $this->count < $this->len;
    }

    public function rewind()
    {
        $this->pre = 1;
        $this->curr = 1;
    }
}

foreach ((new Fb(40)) as $value) {
    echo $value . "\n";
}

PHP生成器

生成器使用yield关键字返回结果,和python一样。yield会直接生产一个结果,下次调用时会从上次yield处继续执行。

function Fb($len)
{
    $pre = 1;
    $curr = 1;
    $count = 1;
    while ($count <= $len) {
        yield $curr;
        $tmp = $curr;
        $curr += $pre;
        $pre = $tmp;
        $count++;
    }
}

foreach (Fb(40) as $value) {
    echo $value . "\n";
}

你可能感兴趣的:(斐波那契数列,使用PHP迭代器、生成器实现(yield))