-
-
Notifications
You must be signed in to change notification settings - Fork 5.6k
Make IteratorSize(::Iterators.Cycle)
not always IsInfinite
and document why
#54187
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: master
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -988,7 +988,13 @@ cycle(xs, n::Integer) = flatten(repeated(xs, n)) | |
|
||
eltype(::Type{Cycle{I}}) where {I} = eltype(I) | ||
IteratorEltype(::Type{Cycle{I}}) where {I} = IteratorEltype(I) | ||
IteratorSize(::Type{Cycle{I}}) where {I} = IsInfinite() # XXX: this is false if iterator ever becomes empty | ||
function IteratorSize(::Type{Cycle{I}}) where I | ||
# TODO: find a better way of communicating the size of a cycle | ||
# IsInfinite() would be false if iterator ever becomes empty | ||
IteratorSize(I) === IsInfinite() ? IsInfinite() : SizeUnknown() | ||
end | ||
IteratorSize(it::Cycle) = isempty(it.xs) ? HasLength() : IsInfinite() | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Do we have other examples where And if There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
No, this is the first case, and changes the docs to suggest the possibility.
IMO that's because Iterators.cycle on stateful iterators is broken. It is explicitly documented to be infinite for non-empty arguments. |
||
length(it::Cycle) = isempty(it.xs) ? 0 : throw(ArgumentError("Cannot compute length of infinite iterator")) | ||
|
||
iterate(it::Cycle) = iterate(it.xs) | ||
isdone(it::Cycle) = isdone(it.xs) | ||
|
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
A refinement, to improve precision:
The idea is that there are two cases when we know the number of elements is not zero (and thus infinite):
IteratorSize(I) === IsInfinite()
, already accounted for, just listing it for completenessIteratorSize(I) === HasShape{0}()
, because a zero-dimensional shape implies a length of exactly one