Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Define counter(::Generator) #302

Merged
merged 3 commits into from
Sep 3, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions doc/source/accumulators.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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::

Expand Down
8 changes: 8 additions & 0 deletions src/accumulator.jl
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
4 changes: 4 additions & 0 deletions test/test_accumulator.jl
Original file line number Diff line number Diff line change
Expand Up @@ -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