On Wed, 20 Mar 2019 at 00:35, Stanislav Malyshev <smalys...@gmail.com>
wrote:

> > And converting from a generator to an array is trivial; the other
> > way, very not so much.
>
> BTW, how it's not trivial to make generator from array?
>
> function generate($array) { foreach($array as $k => $v) yield $k => $v; }
>
> Is there something I'm missing here?
>


It's not that you can't make an array into a generator, but you can't make
an eagerly-evaluated expression into a lazily-evaluated one.

So if you only have array comprehensions, you can use that helper function
to write this, but it will allocate memory for an array containing all the
matches:

$hugeCSVFileIterator = new CSVFileLazyLoader($filename);
$filteredCSVFileIterator = generate([ foreach $hugeCSVFileIterator as $line
if $line['type'] == 'foo' yield $line['value'] ]);

whereas if the comprehension is an iterator, you can do this and preserve
the lazy-loading:

$hugeCSVFileIterator = new  CSVFileLazyLoader($filename);
$filteredCSVFileIterator = [ foreach $hugeCSVFileIterator as $line if
$line['type'] == 'foo' yield $line['value'] ];

Similarly, an array-only syntax is useless for infinite iterators, whereas
an iterator version lets you write a filtered version that's still infinite.

I think a syntax that allows for both versions, using something more
idiomatically PHPish than different types of brackets, might be sensible.
But if we only have one, it should be the iterator version, with a
short-hand for iterator_to_array as a separate language improvement.

Regards,
-- 
Rowan Collins
[IMSoP]

Reply via email to