julia - 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.
解决方案
在这里 - 您只需提供默认值作为一个元素元组:
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)
推荐阅读
- python - 无法在 Visual Studio 2013 中设置 Python2
- angular - 在 Ionic 4 中调用 complete() 时,无限滚动不起作用
- c# - 如何为整个 winform 应用程序中使用的数据表设置日期时间格式?
- r - 先验内存不足
- sql - SQL Server 中受影响的行的详细信息
- node.js - 更改列名 Sequilize
- android - 在不同驱动器上安装 android studio 时的 Android sdk 位置
- curl - 命令池如何工作?以及我们如何重定向到支付网关?Magento 2
- php - 如何在PHP中按其他列获取表组中的数据
- ios - 错误:没有这样的功能:iOS 上的 sqlcipher_export