5

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.

Community
  • 1
  • 1
Colin T Bowers
  • 18,106
  • 8
  • 61
  • 89

1 Answers1

4

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)

ajkeith
  • 28
  • 1
  • 4
IainDunning
  • 11,546
  • 28
  • 43
  • Interesting. I didn't realise the sub-type operator could be used on the union of non-nested types like that. Thanks. I suppose this implies that something like `AnotherFunc{T::Union(Float64, String)}(x::Array{T, 1})` would be preferred to `AnotherFunc(Union(Array{Float64, 1}, Array{String, 1}))`, is this correct? Thanks again. – Colin T Bowers Dec 01 '14 at 01:26
  • 2
    I think that'd be just a matter of readability, although for this particular example with two arguments, they'd actually mean different things. The parametric version would require both arrays to have the same element type, but the one where each argument is union-typed would allow `x` and `y` to be different – IainDunning Dec 01 '14 at 01:30