Skip to content

Commit

Permalink
Implement pairs like PR 22907
Browse files Browse the repository at this point in the history
  • Loading branch information
iamed2 committed Dec 5, 2017
1 parent 602c43a commit 6f043aa
Show file tree
Hide file tree
Showing 2 changed files with 73 additions and 0 deletions.
45 changes: 45 additions & 0 deletions src/Compat.jl
Original file line number Diff line number Diff line change
Expand Up @@ -663,6 +663,51 @@ end
export partialsort, partialsort!, partialsortperm, partialsortperm!
end

# 0.7.0-DEV.1660
@static if !isdefined(Base, :pairs)
pairs(collection) = Base.Generator(=>, keys(collection), values(collection))
pairs(a::Associative) = a

# 0.6.0-dev+2834
@static if !isdefined(Iterators, :IndexValue)
include_string(@__MODULE__, """
immutable IndexValue{I,A<:AbstractArray}
data::A
itr::I
end
""")

Base.length(v::IndexValue) = length(v.itr)
Base.indices(v::IndexValue) = indices(v.itr)
Base.size(v::IndexValue) = size(v.itr)
@inline Base.start(v::IndexValue) = start(v.itr)
Base.@propagate_inbounds function Base.next(v::IndexValue, state)
indx, n = next(v.itr, state)
item = v.data[indx]
(indx => item), n
end
@inline Base.done(v::IndexValue, state) = done(v.itr, state)

Base.eltype{I,A}(::Type{IndexValue{I,A}}) = Pair{eltype(I), eltype(A)}

Base.iteratorsize{I}(::Type{IndexValue{I}}) = iteratorsize(I)
Base.iteratoreltype{I}(::Type{IndexValue{I}}) = iteratoreltype(I)

Base.reverse(v::IndexValue) = IndexValue(v.data, reverse(v.itr))
else
const IndexValue = Iterators.IndexValue
end

pairs(::IndexLinear, A::AbstractArray) = IndexValue(A, linearindices(A))
pairs(::IndexCartesian, A::AbstractArray) = IndexValue(A, CartesianRange(indices(A)))

Base.keys(a::AbstractArray) = CartesianRange(indices(a))
Base.keys(a::AbstractVector) = linearindices(a)
Base.keys(s::IndexStyle, A::AbstractArray, B::AbstractArray...) = eachindex(s, A, B...)

Base.values(itr) = itr
end

# 0.7.0-DEV.1721
@static if !isdefined(Base, :AbstractRange)
const AbstractRange = Range
Expand Down
28 changes: 28 additions & 0 deletions test/runtests.jl
Original file line number Diff line number Diff line change
Expand Up @@ -733,6 +733,34 @@ let x = fill!(StringVector(5), 0x61)
@test pointer(x) == pointer(String(x))
end

# PR 22907
using Compat: pairs

# keys, values, pairs
for A in (rand(2), rand(2,3))
local A
for (i, v) in pairs(A)
@test A[i] == v
end
@test collect(values(A)) == collect(A)
end

let A = Dict(:foo=>1, :bar=>3)
for (k, v) in pairs(A)
@test A[k] == v
end
@test sort!(collect(pairs(A))) == sort!(collect(A))
end

let
A14 = [11 13; 12 14]
R = CartesianRange(indices(A14))
@test [a for (a,b) in pairs(IndexLinear(), A14)] == [1,2,3,4]
@test [a for (a,b) in pairs(IndexCartesian(), A14)] == vec(collect(R))
@test [b for (a,b) in pairs(IndexLinear(), A14)] == [11,12,13,14]
@test [b for (a,b) in pairs(IndexCartesian(), A14)] == [11,12,13,14]
end

# Val(x)
# 0.7
begin
Expand Down

0 comments on commit 6f043aa

Please sign in to comment.