comparison src/StaticDicts/StaticDicts.jl @ 736:b5d9fbcdcef1 feature/static_dict

Add a constuctor taking a tuple
author Jonatan Werpers <jonatan@werpers.com>
date Wed, 17 Mar 2021 21:45:59 +0100
parents 3e0b0b44868e
children ca4f17efb279
comparison
equal deleted inserted replaced
735:3e0b0b44868e 736:b5d9fbcdcef1
21 to the constructor. 21 to the constructor.
22 """ 22 """
23 struct StaticDict{K,V,N} <: AbstractDict{K,V} 23 struct StaticDict{K,V,N} <: AbstractDict{K,V}
24 pairs::NTuple{N,Pair{K,V}} 24 pairs::NTuple{N,Pair{K,V}}
25 25
26 # TBD: Why doesn't `pairs::NTuple{N,Pair{K,V}}` work?
27 function StaticDict{K,V,N}(pairs::Tuple) where {K,V,N} 26 function StaticDict{K,V,N}(pairs::Tuple) where {K,V,N}
28 if !allunique(first.(pairs)) 27 if !allunique(first.(pairs))
29 throw(ArgumentError("keys must be unique (for now)")) 28 throw(ArgumentError("keys must be unique (for now)"))
30 end 29 end
31
32 return new{K,V,N}(pairs) 30 return new{K,V,N}(pairs)
33 end 31 end
34 end 32 end
35 33
36 function StaticDict(pairs::Vararg{Pair}) 34 function StaticDict(pairs::Vararg{Pair})
37 K = typejoin(firsttype.(pairs)...) 35 K = typejoin(firsttype.(pairs)...)
38 V = typejoin(secondtype.(pairs)...) 36 V = typejoin(secondtype.(pairs)...)
39 N = length(pairs) 37 N = length(pairs)
40 return StaticDict{K,V,N}(pairs) 38 return StaticDict{K,V,N}(pairs)
41 end 39 end
40
41 StaticDict(pairs::NTuple{N,Pair} where N) = StaticDict(pairs...)
42 42
43 function Base.get(d::StaticDict, key, default) 43 function Base.get(d::StaticDict, key, default)
44 for p ∈ d.pairs # TBD: Is this the best? Should we use the iterator on `d`? 44 for p ∈ d.pairs # TBD: Is this the best? Should we use the iterator on `d`?
45 if key == p.first 45 if key == p.first
46 return p.second 46 return p.second