Skip to content
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

Add a default implementation of length using iterate. #35947

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
1 change: 1 addition & 0 deletions NEWS.md
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ Standard library changes
------------------------
* The `nextprod` function now accepts tuples and other array types for its first argument ([#35791]).
* The function `isapprox(x,y)` now accepts the `norm` keyword argument also for numeric (i.e., non-array) arguments `x` and `y` ([#35883]).
* There is a default implementation of `length` for all iterables with `IteratorSize` of `SizeUnknown` (using simple iteration) ([#35947]).

#### LinearAlgebra

Expand Down
12 changes: 12 additions & 0 deletions base/generator.jl
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,18 @@ IteratorSize(::Type{Any}) = SizeUnknown()

haslength(iter) = IteratorSize(iter) isa Union{HasShape, HasLength}

function length(iter)
if IteratorSize(iter) isa SizeUnknown
i = 0
for _ in iter
i += 1
end
return i
else
throw(MethodError(length, (iter,)))
end
end

abstract type IteratorEltype end
struct EltypeUnknown <: IteratorEltype end
struct HasEltype <: IteratorEltype end
Expand Down
1 change: 1 addition & 0 deletions test/missing.jl
Original file line number Diff line number Diff line change
Expand Up @@ -363,6 +363,7 @@ end
@testset "skipmissing" begin
x = skipmissing([1, 2, missing, 4])
@test eltype(x) === Int
@test length(x) == 3
@test collect(x) == [1, 2, 4]
@test collect(x) isa Vector{Int}

Expand Down