Dispatch over element type

Hi all, and thank you again :slight_smile:

Can you elaborate on why you think it’s not? For instance, I think I would agree with you if f was an internal function used in some performance-critic part of the code. But (and maybe it’s a useful piece of context indeed:) this is a public API. If I had to describe the design in a nutshell: I don’t want to state unnecessary constraints on my function signature.
All I’m needing here is that collection yields items in an iterable fashion, i.e. for i in collection should not error. As a consequence, I would be unsatisfied to force my callers into using a Vector rather than anything they have at hand like a Tuple, a Set or a lazy iterator.
This being said, and since performance is not a concern, I would agree that converting the received argument to some standard collection like Vector could be useful indeed:

f(collection) = f(Vector(collection))
f(collection::Vector{<:Integer}) = # implement for integers
f(collection::Vector{<:AbstractString}) = # implement for strings
f(::Vector) = throw(ArgumentError("Invalid element type.."))

But I find this somewhat unsatisfying because Vector is only introduced/allocated here for dispatching purpose. Dispatching should not influence implementation this way, right?

This is also what I think. if eltype(collection) <: Integer is a good way to go if I’m not willing to include the third-party @trait macro here.

Oh, I didn’t know about those :smiley: This is very close to the perfect solution because it’s semantically accurate and only uses native Julia concepts. Although it’s a little bit complicated for a small function with only a few expected possible element types, I would definitely go for it if the list of expected possible types needs to be large, or open. Maybe I need to read that part of the docs now?

1 Like