如何解决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.
,但这显然是错误的,因为它默认为Float
而不是Tuple
。如果未明确提供参数,我该如何声明我希望将N
长元组作为可选参数,默认将所有元素默认为0.
?
解决方法
在这里-您只需提供默认值作为一个元素元组即可:
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,5))
ERROR: MethodError: no method matching #somefun#1(::Tuple{Float64},::typeof(somefun),::Int64,::Tuple{Int64,Int64})
如果要解决此问题,则需要另一个构造函数:
function somefun(d::Int64,N}}= tuple(zeros(length(n))...)) where N
println("d=$d n=$n xmin=$xmin")
end
测试:
julia> somefun(4,5))
d=4 n=(4,5) xmin=(0.0,0.0)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。