首页 > 解决方案 > N 长元组作为可选参数

问题描述

我想有一个N长元组作为函数的可选参数,但我不知道如何提供N长默认值:

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

我知道xmin应该用默认值声明,例如xmin::Tuple{Vararg{Float64, N}}::0.,但这显然是错误的,因为它默认为 aFloat而不是Tuple. 如果未显式提供参数,我如何声明我想要一个N长元组作为可选参数,默认为(例如)所有元素?0.

标签: julia

解决方案


在这里 - 您只需提供默认值作为一个元素元组:

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

要了解它的工作原理,请注意:

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

所以你需要 1 元素元组作为默认值。

让我们测试一下:

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

这按预期工作。

最后,请注意,提供一个 2 元素元组作为第二个参数而不提供第三个参数将引发错误,因为大小不匹配:

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

如果要解决此问题,则需要另一个构造函数:

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

测试:

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

推荐阅读