Limit argument types of a function

Hi,
Is the below example the “best” way to limit the types that can be passed to a function?
I would like to only allow Int64 and Float64, i.e. I want the function definition to be either vadd(::Float64,::Float64) or vadd(::Float64,::Float64). I don’t want to allow vadd(::Float64,::Int64) for example.

module TT

const tt = Union{Float64, Int64}

function vadd(a::T, b::T) where T <:tt
  return a+b+oneunit(T)
end

end

Thank you

Looks good to me. You don’t need the alias tt but I’m guessing you’ll reuse that union frequently.

2 Likes

You code looks fine. Is there anything in particular you dislike? Depending on your application, it could be that just checking if the types are the same is sufficient, e.g. vadd(a::T, b::T) where {T}. That way you code remains a bit more generic. (But like Benny said, nothing wrong with your approach.)

3 Likes

As a side note, I would capitalize tt (so Tt or another name starting with uppercase), as it is the identifier of a type, and per style guide they should be capitalized.

2 Likes

Thank you guys. Nothing that I dislike. I just wanted to be sure that it is the proper way to do.

I would add that this also solves the problem of the mixed float and int input:

julia> f(a::T,b::T) where T = 1
f (generic function with 1 method)

julia> f(1, 1.0)
ERROR: MethodError: no method matching f(::Int64, ::Float64)

while still remaining general such that Float32s, or Int32 are also accepted, for example (it may be that the definition of the union type is not necessary for what you want).

1 Like