如何传递一个空的生成器参数? [英] How to pass in an empty generator parameter?
问题描述
我有一个方法,该方法需要一个生成器以及一些其他参数,然后返回一个新的生成器:
I have a method which takes a generator plus some additional parameters and returns a new generator:
function merge(\Generator $carry, array $additional)
{
foreach ( $carry as $item ) {
yield $item;
}
foreach ( $additional as $item ) {
yield $item;
}
}
此功能的常用用例类似于此:
The usual use case for this function is similar to this:
function source()
{
for ( $i = 0; $i < 3; $i++ ) {
yield $i;
}
}
foreach ( merge(source(), [4, 5]) as $item ) {
var_dump($item);
}
但是问题是有时我需要将空源传递给merge
方法.理想情况下,我希望能够执行以下操作:
But the problem is that sometimes I need to pass empty source to the merge
method. Ideally I would like to be able to do something like this:
merge(\Generator::getEmpty(), [4, 5]);
这正是我在C#中的做法(有一个IEnumerable<T>.Empty
属性).但我在手册中看不到任何empty
生成器
Which is exactly how I would do in C# (there is a IEnumerable<T>.Empty
property). But I don't see any kind of empty
generator in the manual.
我已经使用此功能设法解决了这个问题(目前):
I've managed to work around this (for now) by using this function:
function sourceEmpty()
{
if ( false ) {
yield;
}
}
这有效.代码:
foreach ( merge(sourceEmpty(), [4, 5]) as $item ) {
var_dump($item);
}
正确输出:
int(4)
int(5)
但这显然不是理想的解决方案.将空生成器传递给merge
方法的正确方法是什么?
But this is obviously not an ideal solution. What would be the proper way of passing an empty generator to the merge
method?
推荐答案
我找到了解决方法:
由于\Generator
扩展了\Iterator
,因此我可以将方法签名更改为:
Since \Generator
extends \Iterator
I can just change the method signature to this:
function merge(\Iterator $carry, array $additional)
{
// ...
这是输入协方差,因此会破坏向后兼容性,但前提是有人确实扩展了merge
方法.任何调用仍然有效.
This is input covariance thus it would break backward compatibility, but only if someone did extend the merge
method. Any invocations will still work.
现在,我可以使用PHP的本机EmtpyIterator
调用该方法:
Now I can invoke the method with PHP's native EmtpyIterator
:
merge(new \EmptyIterator, [4, 5]);
通常的生成器也可以工作:
And the usual generator also works:
merge(source(), [4, 5])
这篇关于如何传递一个空的生成器参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!