Re: Let range() return a generator?

From: Date: Fri, 17 Mar 2017 06:40:45 +0000
Subject: Re: Let range() return a generator?
References: 1  Groups: php.internals 
Request: Send a blank email to internals+get-98573@lists.php.net to get a copy of this message
> > For me, > > foreach (range($low, $high) as $i) > > is easier to understand than > > for ($i = 0; $i <= $high; $i++) > > By easier to understand I do not only mean that the beginning of the loop > marked by the foreach/range construct is easier to read. While reading the > body of the loop I can be sure that $i is not unexpectedly modified, for > instance. > > Be that as it may, what I would like to propose should be useful for use > cases other than the one (see above) that triggered me thinking about this. > > range() returns an array that contains all elements requested. Depending > on the amount of elements, this might not be optimal. > > One of the most common usages of generators that I have seen is an > alternative, userland implementation of the range() function: > > function xrange($start, $end, $step = 1) { > for ($i = $start; $i <= $end; $i += $step) { > yield $i; > } > } > > This makes me wonder: would there be a benefit in changing the > implementation of range() to return a generator instead of an array? And if > so, would this constitute a break in backward compatibility? Yes, that's a BC break. Instead of changing it, there could be a new function. But as it can be simply built in userland, I don't see much reason to have it in core. Regards, Niklas

« previous php.internals (#98573) next »