forked from JuliaLang/julia
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpair.jl
67 lines (52 loc) · 1.67 KB
/
pair.jl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# This file is a part of Julia. License is MIT: https://julialang.org/license
"""
Pair(x, y)
x => y
Construct a `Pair` object with type `Pair{typeof(x), typeof(y)}`. The elements
are stored in the fields `first` and `second`. They can also be accessed via
iteration.
See also: [`Dict`](@ref)
# Examples
```jldoctest
julia> p = "foo" => 7
"foo" => 7
julia> typeof(p)
Pair{String,Int64}
julia> p.first
"foo"
julia> for x in p
println(x)
end
foo
7
```
"""
struct Pair{A,B}
first::A
second::B
end
const => = Pair
start(p::Pair) = 1
done(p::Pair, i) = i>2
next(p::Pair, i) = (getfield(p,i), i+1)
eltype(p::Type{Pair{A,B}}) where {A,B} = Union{A,B}
indexed_next(p::Pair, i::Int, state) = (getfield(p,i), i+1)
hash(p::Pair, h::UInt) = hash(p.second, hash(p.first, h))
==(p::Pair, q::Pair) = (p.first==q.first) & (p.second==q.second)
isequal(p::Pair, q::Pair) = isequal(p.first,q.first) & isequal(p.second,q.second)
isless(p::Pair, q::Pair) = ifelse(!isequal(p.first,q.first), isless(p.first,q.first),
isless(p.second,q.second))
getindex(p::Pair,i::Int) = getfield(p,i)
getindex(p::Pair,i::Real) = getfield(p, convert(Int, i))
reverse(p::Pair{A,B}) where {A,B} = Pair{B,A}(p.second, p.first)
firstindex(p::Pair) = 1
lastindex(p::Pair) = 2
length(p::Pair) = 2
first(p::Pair) = p.first
last(p::Pair) = p.second
convert(::Type{Pair{A,B}}, x::Pair{A,B}) where {A,B} = x
function convert(::Type{Pair{A,B}}, x::Pair) where {A,B}
Pair{A,B}(convert(A, x[1]), convert(B, x[2]))
end
promote_rule(::Type{Pair{A1,B1}}, ::Type{Pair{A2,B2}}) where {A1,B1,A2,B2} =
Pair{promote_type(A1, A2), promote_type(B1, B2)}