[swift-evolution] [Proposal] Fix lazy filter

Антон Жилин antonyzhilin at gmail.com
Sun Jun 19 14:49:20 CDT 2016


I tested that behavior a bit more.
When lazy is called on non-collection that is converted to Array, it is
iterated once. `underestimatedCount` is not used.
When lazy is called on collection that is converted to Array, `count`
computed property is retrieved. Lazy collection types define `count` as
iterating and filtering through the underlying collection.

I think there are two issues:
1. underestimatedCount should require O(1) complexity. Array initializer
should always call it, as it perfectly suits its purpose
2. For collections, there should be choice to either use underestimateCount
(safe default) or count

The "right" interface should look like:

init<S: SequenceType>(_ s: S)
init<S: CollectionType>(_ c: C, preciseCount: Bool = false)

If getting precise count requires computations (otherwise it would be in
underestimatedCount), but programmer is sure that computations are cheap in
the specific case, he can opt in explicitly.

- Anton

Sun Jun 19 13:03:03 CDT 2016, Haravikk <swift-evolution at haravikk.me> wrote:

> I think I agree that it’s a bug; as stated in the proposal the current
> behaviour allows .underestimatedCount to consume the entire sequence
> because sequences are potentially destructive (so its only possible to
> guarantee access to each element once). Actually, the fact that this hasn’t
> been discovered sooner suggests the current tests don’t include the use of
> destructive sequences, which may need to be considered too, as all Sequence
> methods should work correctly with both destructive and non-destructive
> sequences.
> So yeah, I think having lazy sequences of this type return 0 for
> underestimateCount is the right solution for the time being.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20160619/2f5dac3d/attachment.html>


More information about the swift-evolution mailing list