Skip to content

Implement keys and pairs for Enumerate #48318

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

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion NEWS.md
Original file line number Diff line number Diff line change
Expand Up @@ -39,10 +39,13 @@ Standard library changes

#### Package Manager

- "Package Extensions": support for loading a piece of code based on other
* "Package Extensions": support for loading a piece of code based on other
packages being loaded in the Julia session.
This has similar applications as the Requires.jl package but also
supports precompilation and setting compatibility.
* Iterators returned by `enumerate` now implement the `keys` and `pairs`
functions. ([#48318])

#### LinearAlgebra


Expand Down
7 changes: 7 additions & 0 deletions base/iterators.jl
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
23 changes: 18 additions & 5 deletions test/iterators.jl
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down