I am trying to write a function that takes an argument that can be a tuple or an array. This works for example:
julia> temp(x::Union{Vector{Int64},NTuple{4,Int64}}) = sum(x)
temp (generic function with 1 method)
julia> temp((3,1,5,4))
13
julia> temp([3,1,5,4])
13
On the other hand, when I try to use a tuple of an unspecified length, it fails for the array:
julia> temp(x::Union{Vector{Int64},NTuple{N,Int64}}) where N = sum(x)
temp (generic function with 1 method)
julia> temp([3,1,5,4])
ERROR: MethodError: no method matching temp(::Array{Int64,1})
Closest candidates are:
temp(::Union{Array{Int64,1}, Tuple{Vararg{Int64,N}}}) where N at REPL[1]:1
julia> temp((3,1,5,4))
13
Is this not the way of doing things? I realise that I can solve this using multiple dispatch:
julia> temp(x::Vector{Int64}) = sum(x)
temp (generic function with 1 method)
julia> temp(x::NTuple{N,Int64}) where N = sum(x)
temp (generic function with 2 methods)
julia> temp((3,1,5,4))
13
julia> temp([3,1,5,4])
13
but I am trying to understand how Union works in julia, and wondering if there is a way to achieve this using it.
temp(x::Union{Vector{Int64},NTuple{N,Int64} where N}). - Bogumił Kamiński