How to input types for functions in a more compact way?

Hi,

I am trying to improve the way that I define the input types for my functions in Julia. I have a function that can take as input array values of type Dates.Date, Dates.DateTime or StepRange{Dates.Date, Dates.Day}. See below the example.

Do you know of a more compact way of defining the input types for this function? Could you please also point it out to the source of where you learned this information?

Thanks!

myFunction(x::Union{Array{Dates.Date}, Array{Dates.DateTime}, StepRange{Dates.Date, Dates.Day}})
1 Like

One alternative is to define a type alias,

const AcceptedDateArrays = Union{
    Array{Dates.Date},
    Array{Dates.Day},
    StepRange{Dates.Date, Dates.Day}
}

myfunction(x::AcceptedDateArrays) = ...

that makes it easy to add/remove types later if you want.

Another (more common maybe) alternative is to just let it go, and use:

myfunction(x::AbstractArray) = ...

if an input that that is not adequate is passed on, an error will occur later inside the function. One advantage of this is that your function probably should work with more abstract arrays of the ones defined above, like slices of the arrays of dates, static arrays of dates, etc. Having a general interface like this one allows your function to accept those.

3 Likes

I’ve been using Julia for a few years and it never occured to me that I could use “,” to add multiple type signatures :sweat_smile:

Thank you for asking!

The collection of types seems oddly specific. Why not use something more abstract? For example

AbstractVector{<:TimeType}  # or AbstractArray

?
If you can use a general vector (or N-dim array?!) of times, as well as a range, why not this?

one possibility is you don’t annotate the type at all.

2 Likes