[swift-evolution] Prosposal: LazyCollectionType.prefix() to return a lazy collection

Dmitri Gribenko gribozavr at gmail.com
Sun Feb 14 06:12:55 CST 2016

On Sun, Feb 14, 2016 at 2:51 AM, Mark Aron Szulyovszky via
swift-evolution <swift-evolution at swift.org> wrote:
> Problem:
> .prefix() works eagerly even on LazyCollectionType. This means access is not
> O(1).
> Implications:
> There's no way to only get the first N elements of a lazy sequence without a
> nasty for loop. If prefix() used on a lazy sequence, it'll trigger
> computation on the whole array, just to return the first N elements.
> Proposal:
> It would be more more useful if lazy.<insert methods here>.prefix() returned
> LazyPrefixCollection<Generator.Element>
> instead of
> Slice<LazyCustomCollection<Range<Generator.Element>>>.

Thanks, Mark!

I think this would be a good addition for forward and bidirectional
collections.  You'd need two separate implementations for forward and
bidirectional wrappers.

For random-access collections, the eager implementation is optimal
(finding the end index runs in O(1) and Slice<> does not introduce any
constant factor compared to non-trivial wrappers), and we should keep
that behavior by adding an overload that would return a


(j){printf("%d\n",i);}}} /*Dmitri Gribenko <gribozavr at gmail.com>*/

More information about the swift-evolution mailing list