diff --git a/src/weights.jl b/src/weights.jl index 196a6cd37..b542942b3 100644 --- a/src/weights.jl +++ b/src/weights.jl @@ -1,9 +1,16 @@ ###### Weight vector ##### -immutable WeightVec{W,Vec<:RealVector} - values::Vec - sum::W +if VERSION < v"0.6.0-dev.2123" + immutable WeightVec{S<:Real, T<:Real, V<:RealVector} <: RealVector{T} + values::V + sum::S + end +else + immutable WeightVec{S<:Real, T<:Real, V<:AbstractVector{T}} <: AbstractVector{T} + values::V + sum::S + end end """ @@ -12,8 +19,9 @@ end Construct a `WeightVec` with weight values `vs` and sum of weights `wsum`. If omitted, `wsum` is computed. """ -WeightVec{Vec<:RealVector,W<:Real}(vs::Vec,wsum::W) = WeightVec{W,Vec}(vs, wsum) -WeightVec(vs::RealVector) = WeightVec(vs, sum(vs)) +function WeightVec{S<:Real, V<:RealVector}(vs::V, s::S=sum(vs)) + return WeightVec{S, eltype(vs), V}(vs, s) +end """ weights(vs) @@ -30,6 +38,7 @@ sum(wv::WeightVec) = wv.sum isempty(wv::WeightVec) = isempty(wv.values) Base.getindex(wv::WeightVec, i) = getindex(wv.values, i) +Base.size(wv::WeightVec) = size(wv.values) ##### Weighted sum ##### @@ -281,6 +290,9 @@ Base.mean{T<:Number,W<:Real}(A::AbstractArray{T}, w::WeightVec{W}, dim::Int) = ###### Weighted median ##### +function Base.median(v::AbstractArray, w::WeightVec) + throw(MethodError(median, (v, w))) +end function Base.median{W<:Real}(v::RealVector, w::WeightVec{W}) isempty(v) && error("median of an empty array is undefined") diff --git a/test/weights.jl b/test/weights.jl index a7a873799..f712dc01f 100644 --- a/test/weights.jl +++ b/test/weights.jl @@ -5,10 +5,12 @@ import Compat: view @test isa(weights([1, 2, 3]), WeightVec{Int}) @test isa(weights([1., 2., 3.]), WeightVec{Float64}) - @test isa(weights([1 2 3; 4 5 6]), WeightVec{Int}) +@test isa(WeightVec([1, 2, 3], 6), WeightVec{Int}) + @test isempty(weights(Float64[])) +@test size(weights([1, 2, 3])) == (3,) w = [1., 2., 3.] wv = weights(w) @@ -26,6 +28,11 @@ bv = weights(b) @test sum(bv) === 3 @test !isempty(bv) +ba = BitArray([true, false, true]) +sa = sparsevec([1., 0., 2.]) + +@test sum(ba, wv) === 4.0 +@test sum(sa, wv) === 7.0 ## wsum