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

Allow map to work on Iterators.Pairs #38150

Open
wants to merge 4 commits 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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions base/iterators.jl
Original file line number Diff line number Diff line change
Expand Up @@ -322,6 +322,8 @@ setindex!(v::Pairs, value, key) = (getfield(v, :data)[key] = value; v)
get(v::Pairs, key, default) = get(getfield(v, :data), key, default)
get(f::Base.Callable, v::Pairs, key) = get(f, getfield(v, :data), key)

Base.map(f, v::Pairs) = Base.collect_similar(values(v), Base.generator(f, v))
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This version handles unusual arrays better, probably needs more tests:

julia> using StaticArrays

julia> z = SA[10, 20, 30];

julia> map(pairs(z)) do (ind, val)
         val + ind
       end
3-element MVector{3, Int64} with indices SOneTo(3):
 11
 22
 33

julia> using StructArrays

julia> x = StructArray([(sqr=i^2, str=string(i)) for i in 1:3]);

julia> map(pairs(x)) do (ind, nt)
         (; ind, nt)
       end
3-element StructArray(::Vector{Int64}, ::Vector{NamedTuple{(:sqr, :str), Tuple{Int64, String}}}) with eltype NamedTuple{(:ind, :nt), Tuple{Int64, NamedTuple{(:sqr, :str), Tuple{Int64, String}}}}:
 (ind = 1, nt = (sqr = 1, str = "1"))
 (ind = 2, nt = (sqr = 4, str = "2"))
 (ind = 3, nt = (sqr = 9, str = "3"))

With just collect not collect_similar (as in first commit), a StaticArray lead to a SizedVector, and a StructArray leads to a Vector. I believe that offsets should work with either version:

julia> using OffsetArrays;

julia> y = OffsetArray([10, 20, 30], 4);

julia> map(pairs(y)) do (ind, val)
         val + ind
       end
3-element OffsetArray(::Vector{Int64}, 5:7) with eltype Int64 with indices 5:7:
 15
 26
 37


# zip

struct Zip{Is<:Tuple}
Expand Down
1 change: 1 addition & 0 deletions test/iterators.jl
Original file line number Diff line number Diff line change
Expand Up @@ -700,6 +700,7 @@ end
@test Base.IteratorSize(pairs([1 2;3 4])) isa Base.HasShape{2}
@test isempty(d) || haskey(d, first(keys(d)))
@test collect(v for (k, v) in d) == collect(A)
@test map(last, d) == collect(A)
if A isa NamedTuple
K = Symbol
V = isempty(d) ? Union{} : Float64
Expand Down