Types of arguments within functions

I have writing a function where both arguments can either be an array of Bool, Int64, and String values. I would prefer not to specify both arguments (less space) but rather substitute a substitute Type something like this.

function test(obsv_array::T, pred_array::T) where {T = Union{Array{String,1},Array{Int64,1},Array{Bool,1}}}
     return operation...
end

Do you all have any suggestions to do this?

Also if the Union statement is in poor form please help me a better functional form.

The Union statement is fine. I would do

function test(obsv_array::T, pred_array::T) where {T <: Union{<:AbstractVector{<:String},<:AbstractVector{<:Integer}, <:AbstractVector{Bool}}
...
end

First, note that I wrote AbstractString, and Integer. This is so people can pass different types of Strings, like a SubString. Same with Integer, which is an abstract type.

Second, note that I wrote AbstractVector. This ensures that things like StaticArrays can be passed, rather than ordinary Vectors.

You can see that this gets complicated quickly, which is why I would encourage you not to restrict your input so much. Julia is flexible, and I encourage you to use that.

For instance, what if someone wants to pass skipmissing(x) to your function? This will fail since skipmissing is an iterator and not a vector.

1 Like

Thank you for the detail explanation. Is there any documentation or videos that explains stuff like this? You have given me a lot of to chew on and this was extremely helpful.

One thing to consider would be whether you want anything more than function test(obsv_array::AbstractVector{T}, pred_array::AbstractVector{T}) where T. This is a much looser type check. It only checks that you have 2 vectors with the same eltype. However, unless you have a specific reason to specify types further, this will be just as performant, and is much easier to read.

1 Like