diff --git a/base/iterators.jl b/base/iterators.jl index db11e57e8b26e2..3902be1db9bf35 100644 --- a/base/iterators.jl +++ b/base/iterators.jl @@ -225,6 +225,13 @@ end (i, n[1]), (i-1, ri, n[2]) end +keys(e::Enumerate) = OneTo(length(e.itr)) + +# This will work even when keys doesn't (due to length being undefined) +pairs(e::Enumerate) = map(e) do (i, el) + Pair(i, el) +end + """ pairs(IndexLinear(), A) pairs(IndexCartesian(), A) diff --git a/test/iterators.jl b/test/iterators.jl index 59588bdac96840..c391e97d4d4d6e 100644 --- a/test/iterators.jl +++ b/test/iterators.jl @@ -80,12 +80,25 @@ let b = IOBuffer("foo\n") @test collect(Base.EachLine(b, keep=true, ondone=()->0)) == ["foo\n"] end -# enumerate (issue #6284) -let b = IOBuffer("1\n2\n3\n"), a = [] - for (i,x) in enumerate(eachline(b)) - push!(a, (i,x)) +@testset "Iterators.enumerate" begin + # issue #6284 + let b = IOBuffer("1\n2\n3\n"), a = [] + for (i,x) in enumerate(eachline(b)) + push!(a, (i,x)) + end + @test a == [(1,"1"),(2,"2"),(3,"3")] + end + + # keys and pairs + let it = enumerate(zip(1:2, 3:4)) + @test collect(keys(it)) == [1, 2] + @test collect(pairs(it)) == [1=>(1,3), 2=>(2,4)] + end + + # pairs when length (and hence keys) is undefined + let b = IOBuffer("1\n2\n3\n"), it=enumerate(eachline(b)) + @test collect(pairs(it)) == [1=>"1", 2=>"2", 3=>"3"] end - @test a == [(1,"1"),(2,"2"),(3,"3")] end # zip eachline (issue #7369)