'Adding StatsBase.jl weights methods to a function in Julia
I am trying to add methods to a function similar to the example function my_function below. These methods should be dispatched when any of the subtypes of AbstractWeights from the StatsBase.jl package are passed.
I don't encounter any problem when writing the example function with Abstract and Primitive types from the Base package. E.g.
function my_function(v::Array{<:Real,1})
return sum(v .* 3)/length(v)
end
function my_function(v::Array{<:Real,1}, w::Array{<:Real,1})
return sum(v .* w .* 3)/sum(w)
end
v = [1,2,3]
w = [3,2,1]
my_function(v)
# 6.0
my_function(v, w)
# 5.0
However, when adding the methods for the types from StatsBase.jl I get MethodError errors:
using StatsBase
my_function(v::Array{<:Real,1}, w::Array{<:AbstractWeights,1}) = my_function(v,w)
my_function(v::Array{<:Real,1}, w::Array{Weights,1}) = my_function(v,w)
my_function(v, pweights(w))
# ERROR: LoadError: MethodError: no method matching my_function(::Vector{Int64}, ::ProbabilityWeights{Int64, Int64, Vector{Int64}})
my_function(v, weights(w))
# ERROR: LoadError: MethodError: no method matching my_function(::Vector{Int64}, ::Weights{Int64, Int64, Vector{Int64}})
How can I write the methods for the StatsBase.jl weights types above?
If the function worked well, the following should be true
my_function(v, w) == my_function(v, weights(w)) == my_function(v, pweights(w)) == my_function(v, fweights(w))
# true
Solution 1:[1]
There are several issues here:
AbstractWeightsis already a vector, so you do not need to wrap it in a vector;- your implementation is recursive (the method calls itself).
So the way you should implement the code is:
my_function(v::Vector{<:Real}, w::AbstractWeights) = sum(v .* w .* 3)/sum(w)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Bogumił Kamiński |
