[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

.prefix() works eagerly even on LazyCollectionType. This means access is
not O(1).

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.

It would be more more useful if lazy.<insert methods here>.prefix() returned
instead of

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

Thanks a lot!

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