Defining one function to input many types in Julia

Setup: I have a function in Julia that takes two inputs, x

and y

. Both inputs are arrays of the same type, where this type can be any number type, Date, DateTime, or String. Please note that the contents of the function are identical regardless of any of the above element types of the input arrays, so I don't want to write the function more than once. I currently have a function defined like this:

function MyFunc{T<:Number}(x::Array{T, 1}, y::Array{T, 1})

      

Obviously this is for the case of numbers, but not Date, DateTime, or String.

Question: What would be the best practice in Julia to write the first line of a function to accommodate these other types? Please note: performance is important.

My attempt: I could try something like:

function MyFunc{T<:Number}(x::Union(Array{T, 1}, Array{Date, 1}, Array{DateTime, 1}, Array{String, 1}) y::Union(Array{T, 1}, Array{Date, 1}, Array{DateTime, 1}, Array{String, 1}))

      

but that seems awkward (or maybe not?).

Links: I think this is quite closely related to my other Stack Overflow question on Julia which can be found here .

+3


source to share


1 answer


The answer would be to use Union

, ie

function MyFunc{T<:Union(Number,Date,DateTime,String)}(x::Array{T, 1}, y::Array{T, 1})
    @show T
end

      



...

julia> MyFunc([1.0],[2.0])
T => Float64

julia> MyFunc(["Foo"],["Bar"])
T => ASCIIString

      

+2


source







All Articles