-
-
Notifications
You must be signed in to change notification settings - Fork 5.5k
/
abstractdict.jl
624 lines (517 loc) · 16 KB
/
abstractdict.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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
# This file is a part of Julia. License is MIT: https://julialang.org/license
# generic operations on dictionaries
"""
KeyError(key)
An indexing operation into an `AbstractDict` (`Dict`) or `Set` like object tried to access or
delete a non-existent element.
"""
struct KeyError <: Exception
key
end
const secret_table_token = :__c782dbf1cf4d6a2e5e3865d7e95634f2e09b5902__
haskey(d::AbstractDict, k) = in(k, keys(d))
function in(p::Pair, a::AbstractDict, valcmp=(==))
v = get(a, p.first, secret_table_token)
if v !== secret_table_token
return valcmp(v, p.second)
end
return false
end
function in(p, a::AbstractDict)
error("""AbstractDict collections only contain Pairs;
Either look for e.g. A=>B instead, or use the `keys` or `values`
function if you are looking for a key or value respectively.""")
end
function summary(io::IO, t::AbstractDict)
showarg(io, t, true)
if Base.IteratorSize(t) isa HasLength
n = length(t)
print(io, " with ", n, (n==1 ? " entry" : " entries"))
else
print(io, "(...)")
end
end
struct KeySet{K, T <: AbstractDict{K}} <: AbstractSet{K}
dict::T
end
struct ValueIterator{T<:AbstractDict}
dict::T
end
function summary(io::IO, iter::T) where {T<:Union{KeySet,ValueIterator}}
print(io, T.name.name, " for a ")
summary(io, iter.dict)
end
show(io::IO, iter::Union{KeySet,ValueIterator}) = show_vector(io, iter)
length(v::Union{KeySet,ValueIterator}) = length(v.dict)
isempty(v::Union{KeySet,ValueIterator}) = isempty(v.dict)
_tt2(::Type{Pair{A,B}}) where {A,B} = B
eltype(::Type{ValueIterator{D}}) where {D} = _tt2(eltype(D))
function iterate(v::Union{KeySet,ValueIterator}, state...)
y = iterate(v.dict, state...)
y === nothing && return nothing
return (y[1][isa(v, KeySet) ? 1 : 2], y[2])
end
copy(v::KeySet) = copymutable(v)
in(k, v::KeySet) = get(v.dict, k, secret_table_token) !== secret_table_token
"""
keys(iterator)
For an iterator or collection that has keys and values (e.g. arrays and dictionaries),
return an iterator over the keys.
"""
function keys end
"""
keys(a::AbstractDict)
Return an iterator over all keys in a dictionary.
`collect(keys(a))` returns an array of keys.
When the keys are stored internally in a hash table,
as is the case for `Dict`,
the order in which they are returned may vary.
But `keys(a)` and `values(a)` both iterate `a` and
return the elements in the same order.
# Examples
```jldoctest
julia> D = Dict('a'=>2, 'b'=>3)
Dict{Char, Int64} with 2 entries:
'a' => 2
'b' => 3
julia> collect(keys(D))
2-element Vector{Char}:
'a': ASCII/Unicode U+0061 (category Ll: Letter, lowercase)
'b': ASCII/Unicode U+0062 (category Ll: Letter, lowercase)
```
"""
keys(a::AbstractDict) = KeySet(a)
"""
values(a::AbstractDict)
Return an iterator over all values in a collection.
`collect(values(a))` returns an array of values.
When the values are stored internally in a hash table,
as is the case for `Dict`,
the order in which they are returned may vary.
But `keys(a)` and `values(a)` both iterate `a` and
return the elements in the same order.
# Examples
```jldoctest
julia> D = Dict('a'=>2, 'b'=>3)
Dict{Char, Int64} with 2 entries:
'a' => 2
'b' => 3
julia> collect(values(D))
2-element Vector{Int64}:
2
3
```
"""
values(a::AbstractDict) = ValueIterator(a)
"""
pairs(collection)
Return an iterator over `key => value` pairs for any
collection that maps a set of keys to a set of values.
This includes arrays, where the keys are the array indices.
# Examples
```jldoctest
julia> a = Dict(zip(["a", "b", "c"], [1, 2, 3]))
Dict{String, Int64} with 3 entries:
"c" => 3
"b" => 2
"a" => 1
julia> pairs(a)
Dict{String, Int64} with 3 entries:
"c" => 3
"b" => 2
"a" => 1
julia> foreach(println, pairs(["a", "b", "c"]))
1 => "a"
2 => "b"
3 => "c"
julia> (;a=1, b=2, c=3) |> pairs |> collect
3-element Vector{Pair{Symbol, Int64}}:
:a => 1
:b => 2
:c => 3
julia> (;a=1, b=2, c=3) |> collect
3-element Vector{Int64}:
1
2
3
```
"""
pairs(collection) = Generator(=>, keys(collection), values(collection))
pairs(a::AbstractDict) = a
"""
empty(a::AbstractDict, [index_type=keytype(a)], [value_type=valtype(a)])
Create an empty `AbstractDict` container which can accept indices of type `index_type` and
values of type `value_type`. The second and third arguments are optional and default to the
input's `keytype` and `valtype`, respectively. (If only one of the two types is specified,
it is assumed to be the `value_type`, and the `index_type` we default to `keytype(a)`).
Custom `AbstractDict` subtypes may choose which specific dictionary type is best suited to
return for the given index and value types, by specializing on the three-argument signature.
The default is to return an empty `Dict`.
"""
empty(a::AbstractDict) = empty(a, keytype(a), valtype(a))
empty(a::AbstractDict, ::Type{V}) where {V} = empty(a, keytype(a), V) # Note: this is the form which makes sense for `Vector`.
copy(a::AbstractDict) = merge!(empty(a), a)
function copy!(dst::AbstractDict, src::AbstractDict)
dst === src && return dst
merge!(empty!(dst), src)
end
"""
merge!(d::AbstractDict, others::AbstractDict...)
Update collection with pairs from the other collections.
See also [`merge`](@ref).
# Examples
```jldoctest
julia> d1 = Dict(1 => 2, 3 => 4);
julia> d2 = Dict(1 => 4, 4 => 5);
julia> merge!(d1, d2);
julia> d1
Dict{Int64, Int64} with 3 entries:
4 => 5
3 => 4
1 => 4
```
"""
function merge!(d::AbstractDict, others::AbstractDict...)
for other in others
if haslength(d) && haslength(other)
sizehint!(d, length(d) + length(other))
end
for (k,v) in other
d[k] = v
end
end
return d
end
"""
mergewith!(combine, d::AbstractDict, others::AbstractDict...) -> d
mergewith!(combine)
merge!(combine, d::AbstractDict, others::AbstractDict...) -> d
Update collection with pairs from the other collections.
Values with the same key will be combined using the
combiner function. The curried form `mergewith!(combine)` returns the
function `(args...) -> mergewith!(combine, args...)`.
Method `merge!(combine::Union{Function,Type}, args...)` as an alias of
`mergewith!(combine, args...)` is still available for backward
compatibility.
!!! compat "Julia 1.5"
`mergewith!` requires Julia 1.5 or later.
# Examples
```jldoctest
julia> d1 = Dict(1 => 2, 3 => 4);
julia> d2 = Dict(1 => 4, 4 => 5);
julia> mergewith!(+, d1, d2);
julia> d1
Dict{Int64, Int64} with 3 entries:
4 => 5
3 => 4
1 => 6
julia> mergewith!(-, d1, d1);
julia> d1
Dict{Int64, Int64} with 3 entries:
4 => 0
3 => 0
1 => 0
julia> foldl(mergewith!(+), [d1, d2]; init=Dict{Int64, Int64}())
Dict{Int64, Int64} with 3 entries:
4 => 5
3 => 0
1 => 4
```
"""
function mergewith!(combine, d::AbstractDict, others::AbstractDict...)
foldl(mergewith!(combine), others; init = d)
end
function mergewith!(combine, d1::AbstractDict, d2::AbstractDict)
for (k, v) in d2
d1[k] = haskey(d1, k) ? combine(d1[k], v) : v
end
return d1
end
mergewith!(combine) = (args...) -> mergewith!(combine, args...)
merge!(combine::Callable, args...) = mergewith!(combine, args...)
"""
keytype(type)
Get the key type of a dictionary type. Behaves similarly to [`eltype`](@ref).
# Examples
```jldoctest
julia> keytype(Dict(Int32(1) => "foo"))
Int32
```
"""
keytype(::Type{<:AbstractDict{K,V}}) where {K,V} = K
keytype(a::AbstractDict) = keytype(typeof(a))
"""
valtype(type)
Get the value type of a dictionary type. Behaves similarly to [`eltype`](@ref).
# Examples
```jldoctest
julia> valtype(Dict(Int32(1) => "foo"))
String
```
"""
valtype(::Type{<:AbstractDict{K,V}}) where {K,V} = V
valtype(a::AbstractDict) = valtype(typeof(a))
"""
merge(d::AbstractDict, others::AbstractDict...)
Construct a merged collection from the given collections. If necessary, the
types of the resulting collection will be promoted to accommodate the types of
the merged collections. If the same key is present in another collection, the
value for that key will be the value it has in the last collection listed.
See also [`mergewith`](@ref) for custom handling of values with the same key.
# Examples
```jldoctest
julia> a = Dict("foo" => 0.0, "bar" => 42.0)
Dict{String, Float64} with 2 entries:
"bar" => 42.0
"foo" => 0.0
julia> b = Dict("baz" => 17, "bar" => 4711)
Dict{String, Int64} with 2 entries:
"bar" => 4711
"baz" => 17
julia> merge(a, b)
Dict{String, Float64} with 3 entries:
"bar" => 4711.0
"baz" => 17.0
"foo" => 0.0
julia> merge(b, a)
Dict{String, Float64} with 3 entries:
"bar" => 42.0
"baz" => 17.0
"foo" => 0.0
```
"""
merge(d::AbstractDict, others::AbstractDict...) =
merge!(_typeddict(d, others...), others...)
"""
mergewith(combine, d::AbstractDict, others::AbstractDict...)
mergewith(combine)
merge(combine, d::AbstractDict, others::AbstractDict...)
Construct a merged collection from the given collections. If necessary, the
types of the resulting collection will be promoted to accommodate the types of
the merged collections. Values with the same key will be combined using the
combiner function. The curried form `mergewith(combine)` returns the function
`(args...) -> mergewith(combine, args...)`.
Method `merge(combine::Union{Function,Type}, args...)` as an alias of
`mergewith(combine, args...)` is still available for backward compatibility.
!!! compat "Julia 1.5"
`mergewith` requires Julia 1.5 or later.
# Examples
```jldoctest
julia> a = Dict("foo" => 0.0, "bar" => 42.0)
Dict{String, Float64} with 2 entries:
"bar" => 42.0
"foo" => 0.0
julia> b = Dict("baz" => 17, "bar" => 4711)
Dict{String, Int64} with 2 entries:
"bar" => 4711
"baz" => 17
julia> mergewith(+, a, b)
Dict{String, Float64} with 3 entries:
"bar" => 4753.0
"baz" => 17.0
"foo" => 0.0
julia> ans == mergewith(+)(a, b)
true
```
"""
mergewith(combine, d::AbstractDict, others::AbstractDict...) =
mergewith!(combine, _typeddict(d, others...), others...)
mergewith(combine) = (args...) -> mergewith(combine, args...)
merge(combine::Callable, d::AbstractDict, others::AbstractDict...) =
merge!(combine, _typeddict(d, others...), others...)
promoteK(K) = K
promoteV(V) = V
promoteK(K, d, ds...) = promoteK(promote_type(K, keytype(d)), ds...)
promoteV(V, d, ds...) = promoteV(promote_type(V, valtype(d)), ds...)
function _typeddict(d::AbstractDict, others::AbstractDict...)
K = promoteK(keytype(d), others...)
V = promoteV(valtype(d), others...)
Dict{K,V}(d)
end
"""
filter!(f, d::AbstractDict)
Update `d`, removing elements for which `f` is `false`.
The function `f` is passed `key=>value` pairs.
# Example
```jldoctest
julia> d = Dict(1=>"a", 2=>"b", 3=>"c")
Dict{Int64, String} with 3 entries:
2 => "b"
3 => "c"
1 => "a"
julia> filter!(p->isodd(p.first), d)
Dict{Int64, String} with 2 entries:
3 => "c"
1 => "a"
```
"""
function filter!(f, d::AbstractDict)
badkeys = Vector{keytype(d)}()
for pair in d
# don't delete!(d, k) here, since dictionary types
# may not support mutation during iteration
f(pair) || push!(badkeys, pair.first)
end
for k in badkeys
delete!(d, k)
end
return d
end
function filter_in_one_pass!(f, d::AbstractDict)
for pair in d
if !f(pair)
delete!(d, pair.first)
end
end
return d
end
"""
filter(f, d::AbstractDict)
Return a copy of `d`, removing elements for which `f` is `false`.
The function `f` is passed `key=>value` pairs.
# Examples
```jldoctest
julia> d = Dict(1=>"a", 2=>"b")
Dict{Int64, String} with 2 entries:
2 => "b"
1 => "a"
julia> filter(p->isodd(p.first), d)
Dict{Int64, String} with 1 entry:
1 => "a"
```
"""
function filter(f, d::AbstractDict)
# don't just do filter!(f, copy(d)): avoid making a whole copy of d
df = empty(d)
for pair in d
if f(pair)
df[pair.first] = pair.second
end
end
return df
end
function eltype(::Type{<:AbstractDict{K,V}}) where {K,V}
if @isdefined(K)
if @isdefined(V)
return Pair{K,V}
else
return Pair{K}
end
elseif @isdefined(V)
return Pair{k,V} where k
else
return Pair
end
end
function isequal(l::AbstractDict, r::AbstractDict)
l === r && return true
if isa(l,IdDict) != isa(r,IdDict)
return false
end
if length(l) != length(r) return false end
for pair in l
if !in(pair, r, isequal)
return false
end
end
true
end
function ==(l::AbstractDict, r::AbstractDict)
if isa(l,IdDict) != isa(r,IdDict)
return false
end
length(l) != length(r) && return false
anymissing = false
for pair in l
isin = in(pair, r)
if ismissing(isin)
anymissing = true
elseif !isin
return false
end
end
return anymissing ? missing : true
end
# Fallback implementation
sizehint!(d::AbstractDict, n) = d
const hasha_seed = UInt === UInt64 ? 0x6d35bb51952d5539 : 0x952d5539
function hash(a::AbstractDict, h::UInt)
hv = hasha_seed
for (k,v) in a
hv ⊻= hash(k, hash(v))
end
hash(hv, h)
end
function getindex(t::AbstractDict, key)
v = get(t, key, secret_table_token)
if v === secret_table_token
throw(KeyError(key))
end
return v
end
# t[k1,k2,ks...] is syntactic sugar for t[(k1,k2,ks...)]. (Note
# that we need to avoid dispatch loops if setindex!(t,v,k) is not defined.)
getindex(t::AbstractDict, k1, k2, ks...) = getindex(t, tuple(k1,k2,ks...))
setindex!(t::AbstractDict, v, k1, k2, ks...) = setindex!(t, v, tuple(k1,k2,ks...))
get!(t::AbstractDict, key, default) = get!(() -> default, t, key)
function get!(default::Callable, t::AbstractDict{K,V}, key) where K where V
haskey(t, key) && return t[key]
val = default()
t[key] = val
return val
end
push!(t::AbstractDict, p::Pair) = setindex!(t, p.second, p.first)
push!(t::AbstractDict, p::Pair, q::Pair) = push!(push!(t, p), q)
push!(t::AbstractDict, p::Pair, q::Pair, r::Pair...) = push!(push!(push!(t, p), q), r...)
# AbstractDicts are convertible
convert(::Type{T}, x::T) where {T<:AbstractDict} = x
function convert(::Type{T}, x::AbstractDict) where T<:AbstractDict
h = T(x)
if length(h) != length(x)
error("key collision during dictionary conversion")
end
return h
end
# hashing objects by identity
_tablesz(x::Integer) = x < 16 ? 16 : one(x)<<((sizeof(x)<<3)-leading_zeros(x-1))
TP{K,V} = Union{Type{Tuple{K,V}},Type{Pair{K,V}}}
dict_with_eltype(DT_apply, kv, ::TP{K,V}) where {K,V} = DT_apply(K, V)(kv)
dict_with_eltype(DT_apply, kv::Generator, ::TP{K,V}) where {K,V} = DT_apply(K, V)(kv)
dict_with_eltype(DT_apply, ::Type{Pair{K,V}}) where {K,V} = DT_apply(K, V)()
dict_with_eltype(DT_apply, ::Type) = DT_apply(Any, Any)()
dict_with_eltype(DT_apply::F, kv, t) where {F} = grow_to!(dict_with_eltype(DT_apply, @default_eltype(typeof(kv))), kv)
function dict_with_eltype(DT_apply::F, kv::Generator, t) where F
T = @default_eltype(kv)
if T <: Union{Pair, Tuple{Any, Any}} && isconcretetype(T)
return dict_with_eltype(DT_apply, kv, T)
end
return grow_to!(dict_with_eltype(DT_apply, T), kv)
end
"""
map!(f, values(dict::AbstractDict))
Modifies `dict` by transforming each value from `val` to `f(val)`.
Note that the type of `dict` cannot be changed: if `f(val)` is not an instance of the value type
of `dict` then it will be converted to the value type if possible and otherwise raise an error.
!!! compat "Julia 1.2"
`map!(f, values(dict::AbstractDict))` requires Julia 1.2 or later.
# Examples
```jldoctest
julia> d = Dict(:a => 1, :b => 2)
Dict{Symbol, Int64} with 2 entries:
:a => 1
:b => 2
julia> map!(v -> v-1, values(d))
ValueIterator for a Dict{Symbol, Int64} with 2 entries. Values:
0
1
```
"""
function map!(f, iter::ValueIterator)
# This is the naive fallback which requires hash evaluations
# Contrary to the example Dict has an implementation which does not require hash evaluations
dict = iter.dict
for (key, val) in pairs(dict)
dict[key] = f(val)
end
return iter
end