From d61810d54837f4f870060741dafe1db96bf9a816 Mon Sep 17 00:00:00 2001 From: Cedric St-Jean Date: Fri, 7 Jul 2017 20:40:02 -0400 Subject: [PATCH] Define counter(::Generator) --- doc/source/accumulators.rst | 2 ++ src/accumulator.jl | 8 ++++++++ test/test_accumulator.jl | 3 +++ 3 files changed, 13 insertions(+) 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 daebc9da9..5295017e1 100644 --- a/src/accumulator.jl +++ b/src/accumulator.jl @@ -24,6 +24,14 @@ function counter{T}(seq::AbstractArray{T}) return ct end +function counter{T<:Base.Generator}(gen::T) + ct = counter(Base._default_eltype(T)) + for x in gen + push!(ct, x) + end + return ct +end + copy{T,V<:Number}(ct::Accumulator{T,V}) = 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 c0ff2ef18..a5ed8556e 100644 --- a/test/test_accumulator.jl +++ b/test/test_accumulator.jl @@ -95,3 +95,6 @@ end @test ct6["a"] == 0 @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))