Size-limited vector type

I want to make a Dict whose keys are view(MVector{5,UInt8}, 1:m) for some m<=5 and , such as

julia> let 
       d = Dict{MVector{5,UInt8}, Int}()
       d[@view((@MVector [1,2,3,4,5])[1:2])] = 1
       end
ERROR: DimensionMismatch("expected input array of length 5, got length 2")

How can I specify the type of this Dict so that its key size is bounded at compile time?

Only way I can think of is to fill the MVector with some kind of sentinel, in this case probably typemin(UInt8) or typemax(UInt8)? But you are then probably on your way to implement SBVector etc. (with B for bounded)…

The easiest way is to let the Dict constructor figure out the type for you by providing at least one key-value pair to the constructor:

julia> d = Dict(@view((@MVector [1,2,3,4,5])[1:2]) => 1)
Dict{SubArray{Int64, 1, MVector{5, Int64}, Tuple{UnitRange{Int64}}, true}, Int64} with 1 entry:
  [1, 2] => 1

julia> d[@view((@MVector [1,2,3,4,5])[1:3])] = 2
2

julia> d
Dict{SubArray{Int64, 1, MVector{5, Int64}, Tuple{UnitRange{Int64}}, true}, Int64} with 2 entries:
  [1, 2, 3] => 2
  [1, 2]    => 1

The other option is to use typeof:

julia> T = typeof(@view((@MVector [1,2,3,4,5])[1:2]))
SubArray{Int64, 1, MVector{5, Int64}, Tuple{UnitRange{Int64}}, true}

julia> d = Dict{T, Int}()
Dict{SubArray{Int64, 1, MVector{5, Int64}, Tuple{UnitRange{Int64}}, true}, Int64}()

Generally you don’t want to try to write down complicated types like SubArray{Int64, 1, MVector{5, Int64}, Tuple{UnitRange{Int64}}, true} by hand, especially if they are types that come from somebody else’s package. Also, in many cases, the exact details of a type signature are not part of the public API—they’re just implementation details.

1 Like

I just read somewhere that mutable dictionary keys are a bad idea. Why can’t you use SVector instead of MVector?

1 Like