在朱莉娅中键入kwargs [英] Typed kwargs in Julia
问题描述
是否可以在Julia中键入函数kwargs?
以下内容适用于标准Vararg
.
function int_args(args::Integer...)
args
end
int_args(1, 2, 3)
# (1, 2, 3)
int_args(1, 2, 3.0)
# ERROR: MethodError: `int_args` has no method matching int_args(::Int64, ::Int64, ::Float64)
但是,将相同的语法应用于kwargs时,所有函数调用似乎都出错.
function int_kwargs(; kwargs::Integer...)
kwargs
end
int_kwargs(x=1, y=2)
# ERROR: MethodError: `__int_kwargs#0__` has no method matching __int_kwargs#0__(::Array{Any,1})
普通关键字参数可以具有类型,如function f(x; a::Int=0)
所示,但这不适用于其余"关键字参数.还要注意,由于我们当前不分派关键字参数,因此在这种情况下,a::Int
是类型声明,而不是分派规范.
看起来这种情况不能很好地处理,并且至少需要更好的错误消息.我鼓励您在 https://github.com/JuliaLang/julia/issues 上提出问题.. >
我不确定关键字参数的语法x::T...
应该意味着什么.对于varargs,很明显x
的每个元素都应具有T
类型,但是对于rest关键字参数,每个元素实际上是一个符号-值对.当然,我们可以给它提供您所描述的含义(所有值的类型均为T
),但这似乎很少出现.关键字参数往往是非常不同的,与varargs不同,而varargs更像是列表或数组.
Is it possible to type function kwargs in Julia?
The following works for standard Vararg
s.
function int_args(args::Integer...)
args
end
int_args(1, 2, 3)
# (1, 2, 3)
int_args(1, 2, 3.0)
# ERROR: MethodError: `int_args` has no method matching int_args(::Int64, ::Int64, ::Float64)
However, when applying this same syntax to kwargs, all function calls seem to error.
function int_kwargs(; kwargs::Integer...)
kwargs
end
int_kwargs(x=1, y=2)
# ERROR: MethodError: `__int_kwargs#0__` has no method matching __int_kwargs#0__(::Array{Any,1})
Normal keyword arguments can have types, as in function f(x; a::Int=0)
, but this doesn't work for "rest" keyword arguments. Also note that since we currently don't dispatch on keyword arguments, the a::Int
in this case is a type assertion and not a dispatch specification.
It looks like this case is not handled well, and needs a better error message at least. I'd encourage you to file an issue at https://github.com/JuliaLang/julia/issues.
I'm not sure what the syntax x::T...
should mean for keyword arguments. In the case of varargs, it's clear that each element of x
should have type T
, but for rest keyword arguments each element is actually a symbol-value pair. Of course we could give it the meaning you describe (all values have type T
), but this doesn't seem to come up very often. Keyword arguments tend to be quite heterogeneous, unlike varargs which are more like lists or arrays.
这篇关于在朱莉娅中键入kwargs的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!