juliatype-declaration

Type declaration in Julia for function argument that can be both array and scalar


What type should I specify in Julia for function arguments that can be either scalars or arrays? For instance, in the function below x and y could be e.g. Float64 or Array{Float64}.

function myfun(x, y)
    return x .+ y
end

Is there an appropriate type declaration for such variables? Or should I just refrain from declaring the type there (or writing functions that are that generic)?


Solution

  • You can safely refrain from specifying types. This will not have an impact on performance of your code.

    However, if you want to explicitly specify the type restriction you provided do (this is mostly useful to make sure your function is called with proper arguments and fail fast if it is not):

    function myfun(x::Union{Float64, Array{Float64}},
                   y::Union{Float64, Array{Float64}})
        return x .+ y
    end
    

    However, most likely you will rather want the following signature:

    function myfun(x::Union{AbstractFloat, AbstractArray{<:AbstractFloat}},
                   y::Union{AbstractFloat, AbstractArray{<:AbstractFloat}})
        return x .+ y
    end
    

    which says you accept any scalar float or any array of floats (not necessarily only Float64 and Array). This is more flexible, as e.g. you can accept views then or other floats (BigFloat or Float32) if you prefer to switch precision of your computations. Such a signature clearly signals your users what types of inputs you expect them to pass to myfun while remaining flexible.

    I recommend this as being overly restrictive (Union{Float64, Array{Float64}}), while accepted by the compiler, usually leads to problems later when you start using your function with various input types.