Skip to content

Commit

Permalink
Add a default implementation of length using iterate.
Browse files Browse the repository at this point in the history
  • Loading branch information
andyferris committed May 20, 2020
1 parent 9d70d45 commit 4ae9169
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 0 deletions.
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

0 comments on commit 4ae9169

Please sign in to comment.