diff --git a/doc/source/accumulators.rst b/doc/source/accumulators.rst index 80788c696..9712db3f4 100644 --- a/doc/source/accumulators.rst +++ b/doc/source/accumulators.rst @@ -26,6 +26,8 @@ There are different ways to construct an accumulator/counter:: a = counter(seq) # construct a counter by counting keys in a sequence + a = counter(gen) # construct a counter by counting keys in a generator + Usage of an accumulator/counter:: diff --git a/src/accumulator.jl b/src/accumulator.jl index 6437765e7..6d0ad79ab 100644 --- a/src/accumulator.jl +++ b/src/accumulator.jl @@ -24,6 +24,14 @@ function counter(seq::AbstractArray{T}) where T return ct end +function counter(gen::T) where {T<:Base.Generator} + ct = counter(Base._default_eltype(T)) + for x in gen + push!(ct, x) + end + return ct +end + copy(ct::Accumulator{T,V}) where {T,V<:Number} = Accumulator{T,V}(copy(ct.map)) length(a::Accumulator) = length(a.map) diff --git a/test/test_accumulator.jl b/test/test_accumulator.jl index 704c28398..add6ad88e 100644 --- a/test/test_accumulator.jl +++ b/test/test_accumulator.jl @@ -97,8 +97,12 @@ @test ct6["b"] == 0 @test ct6["c"] == 4 + s = ["y", "el", "sol", "se", "fue"] + @test counter(length(x) for x in s) == counter(map(length, s)) + # ambiguity resolution ct7 = counter(Int) @test_throws MethodError push!(ct7, 1=>2) end # @testset Accumulators +