N long tuple as optional argument

Viewed 56

I would like to have an N long tuple as an optional argument of a function but I do not know how to provide a N long default value:

function create_grid(d::Int64, n::Tuple{Vararg{Int64, N}}; xmin::Tuple{Vararg{Float64, N}}) where N

I understand xmin should be declared with a default value such as xmin::Tuple{Vararg{Float64, N}}::0., but this is evidently wrong as it is defaulting to a Float instead of Tuple. How can I state I want a N long tuple as optional argument defaulting to (eg.) 0. for all the elements if the argument is not provided explicitly?

1 Answers

Here it is - you just provide the default as a one element tuple:

function somefun(d::Int64, n::Tuple{Vararg{Int64, N}}; xmin::Tuple{Vararg{Float64, N}}=(0.0,)) where N
    println("d=$d n=$n xmin=$xmin")
end

To understand how it works just note that:

Tuple{Vararg{Int, 2}} == typeof((2,2)) 
#and
Tuple{Vararg{Int, 1}} == typeof((2,))

so you needed 1-element tuple as a default.

Let's test it:

julia> somefun(4,(4,))
d=4 n=(4,) xmin=(0.0,)

This works as expected.

Finally, note that providing a 2-element tuple as the second argument without the third one will throw an error because the sizes do not match:

julia> somefun(4,(4,5))
ERROR: MethodError: no method matching #somefun#1(::Tuple{Float64}, ::typeof(somefun), ::Int64, ::Tuple{Int64,Int64})

If you want to workaround this you need another constructor:

function somefun(d::Int64, n::Tuple{Vararg{Int64, N}}; xmin::Tuple{Vararg{Float64, N}}= tuple(zeros(length(n))...)) where N
    println("d=$d n=$n xmin=$xmin")
end

Testing:

julia> somefun(4,(4,5))
d=4 n=(4, 5) xmin=(0.0, 0.0)
Related