Skip to content

Commit e1f3d41

Browse files
committed
Add a default implementation of length using iterate.
1 parent 9d70d45 commit e1f3d41

File tree

3 files changed

+14
-0
lines changed

3 files changed

+14
-0
lines changed

NEWS.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,7 @@ Standard library changes
4343
------------------------
4444
* The `nextprod` function now accepts tuples and other array types for its first argument ([#35791]).
4545
* The function `isapprox(x,y)` now accepts the `norm` keyword argument also for numeric (i.e., non-array) arguments `x` and `y` ([#35883]).
46+
* There is a default implementation of `length` for all iterables with `IteratorSize` of `SizeUnknown` (using simple iteration) ([#???]).
4647

4748
#### LinearAlgebra
4849

base/generator.jl

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -97,6 +97,18 @@ IteratorSize(::Type{Any}) = SizeUnknown()
9797

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

100+
function length(iter)
101+
if IteratorSize(iter) isa SizeUnknown
102+
i = 0
103+
for _ in iter
104+
i += 1
105+
end
106+
return i
107+
else
108+
throw(MethodError(length, (iter,)))
109+
end
110+
end
111+
100112
abstract type IteratorEltype end
101113
struct EltypeUnknown <: IteratorEltype end
102114
struct HasEltype <: IteratorEltype end

test/missing.jl

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -363,6 +363,7 @@ end
363363
@testset "skipmissing" begin
364364
x = skipmissing([1, 2, missing, 4])
365365
@test eltype(x) === Int
366+
@test length(x) == 3
366367
@test collect(x) == [1, 2, 4]
367368
@test collect(x) isa Vector{Int}
368369

0 commit comments

Comments
 (0)