What does Dict{T} mean?

Hi!

Here is the tiny project I have in mind so that I get my hands a bit dirty. I would like to extend the functionality of StatsBase.countmap() so that is accepts the Dictionary type aside from the Dict inbuilt data type.
Going to StatsBase.jl/src/count.jl to see how StatsBase.countmap() is implemented I saw that it was based on the addcounts!() function. Here is its definition.

function addcounts!(cm::Dict{T}, x::AbstractArray{T}, wv::AbstractVector{W}) where {T,W<:Real}
    n = length(x)
    length(wv) == n || throw(DimensionMismatch())
    w = values(wv)
    z = zero(W)

    for i = 1 : n
        @inbounds xi = x[i]
        @inbounds wi = w[i]
        cm[xi] = get(cm, xi, z) + wi
    end
    return cm
end

Now, my question is this: How is it possible to have Dict{T} in there that includes a single type for a dictionary within the curly braces? I am trying to find similar code or an explanation of why and how that is ok in Julia docu, but I had not luck. I know it may be a naive question, but I am stuck. Any short explanation/hint/direction would be greatly appreciated.

Thanks!

Alex

2 Likes

Any unspecified type parameters are unconstrained, so it is an abstract type that includes any kind of Dict where the key type is T. Or put another way, Dict{K} means the same thing as Dict{K, V} where V. This method signature will only match if the key type of cm is the same as the element type of x. The value type of cm can be anything.

4 Likes
julia> function print_param(d::Dict{T}) where T
           display(T)
       end
print_param (generic function with 1 method)

julia> print_param(Dict(1=>"hi"))
Int64

Type parameters get filled in from left to right.

3 Likes

Aha! Very interesting…So, the key type T is unconstrained but, at the same time, it is also minimally constrained by the element type of x.
PS: Having this kind of unconstrained types can be really powerful when writing typed grammars for natural language.

Thanks for the code example @Oscar_Smith ! Really useful to get the hang of it!