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

Mark Aron Szulyovszky mark.szulyovszky at gmail.com
Sun Feb 14 04:51:14 CST 2016


*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>>>.

That way prefix() could be used to chain *pure lazy operations*, like
lazy.filter().map().filter().prefix().map() which can be quite useful in
some cases.

I understand that this has implications, and it would make prefix() less
consistent in terms of return type.
But, this pattern seem to be used in this context already - it wouldn't be
a much different than how how lazy.filter() is implemented, since it also
returns a custom LazySequenceType instead of SequenceType.

Has this been considered before? Would there be any cases where this would
create unintended side effects?
As far as I see, it wouldn't change the meaning and behaviour of prefix(),
only would it extend its usefulness.

I submitted a PR to the SwiftSequence library that demonstrates the
implementation:
https://github.com/itchingpixels/SwiftSequence/commit/26101e5aec6c266048bbad4db7b44b9c453f07ca

Thanks a lot!

Mark
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20160214/1c75978c/attachment.html>


More information about the swift-evolution mailing list