It seems like there should be a valid method for a calling count with a character and a string.
count("a", "batman") # returns 2 as expected
count('a', "batman") # ERROR: MethodError: objects of type Char are not callable
count(==('a'), "batman") # returns 2, an annoying workaround
Is there a reason why this count method isn’t supported. Thoughts?
The function that should do the job is this one (from base/regex.jl):
function count(t::Union{AbstractString,Regex}, s::AbstractString; overlap::Bool=false)
n = 0
i, e = firstindex(s), lastindex(s)
while true
r = findnext(t, s, i)
isnothing(r) && break
n += 1
j = overlap || isempty(r) ? first(r) : last(r)
j > e && break
@inbounds i = nextind(s, j)
end
return n
end
If one adds “AbstractChar” to the union, that function would be called and results what is expected:
julia> function mycount(t::Union{AbstractString,Regex,AbstractChar}, s::AbstractString; overlap::Bool=false)
n = 0
i, e = firstindex(s), lastindex(s)
while true
r = findnext(t, s, i)
isnothing(r) && break
n += 1
j = overlap || isempty(r) ? first(r) : last(r)
j > e && break
@inbounds i = nextind(s, j)
end
return n
end
mycount (generic function with 2 methods)
julia> mycount("a","batman")
2
julia> mycount('a',"batman")
2
I am not sure if there is any bad implication on doing that, but it seems a simple fix.
Should we add a new method to findall? The error message is not as bad as that of count , but it seems reasonable to expect findall to find all chars and return their positions.