Reputation: 18580
Setup: I have a function in Julia that takes two inputs, x
and y
. Both inputs are arrays of the same type, where that type can be any number type, Date, DateTime, or String. Note, 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 out more than once. Currently, I have the function defined like this:
function MyFunc{T<:Number}(x::Array{T, 1}, y::Array{T, 1})
Obviously, this takes care of the numbers case, but not Date, DateTime, or String.
Question: What would be best practice in Julia for writing the first line of the function to accommodate these other types? 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 this feels clumsy (or maybe it isn't?).
Links: I guess this is fairly closely related to another of my Stack Overflow questions on Julia that can be found here.
Upvotes: 5
Views: 1045
Reputation: 11664
The answer would be to use a Union
, i.e.
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
(using Julia 0.6.4 syntax...see the stable documentation for current syntax)
Upvotes: 4