英文:
julia - Function doesnt accept a tuple including a function as parameter
问题
I'm having some issue with julia's typing system. Can someone please clarify?
ValidationRule = Tuple{DataType,Symbol}
ValidationRuleWithConversion = Tuple{DataType,Symbol,<:Function}
function validate(rules::Vector{Union{ValidationRule,ValidationRuleWithConversion}})
end
validate([
(String, :name, convert_name),
(String, :age)
])
And more generally this should work somehow:
function myfunc(arg::Tuple{Vararg}) end
myfunc((:name, a -> a.value))
英文:
I'm having some issue with julia's typing system. Can someone please clarify?
ValidationRule = Tuple{DataType,Symbol}
ValidationRuleWithConversion = Tuple{DataType,Symbol,<:Function}
function validate(rules::Vector{Union{ValidationRule,ValidationRuleWithConversion}})
end
validate([
(String, :name, convert_name),
(String, :age)
])
And more generally this should work somehow:
function myfunc(arg::Tuple{Vararg}) end
myfunc((:name, a -> a.value))
答案1
得分: 2
以下是翻译好的内容:
数组使用[a, b, ...]
构建时的元素类型实质上是typejoin(typeof(a), typeof(b), ...)
(忽略了提升规则),在这种情况下意味着元素类型是Tuple{DataType, Symbol, Vararg{typeof(convert_name)}}
。这种类型与您的联合类型不同,因为这里的Vararg
表示任意数量的typeof(convert_name)
。
您可以强制使数组具有正确的类型以使其正常工作:
EitherValidationRule = Union{ValidationRule, ValidationRuleWithConversion}
validate(EitherValidationRule[
(String, :name, convert_name),
(String, :age)
])
但似乎最好为每种类型的验证规则制作一个适当的结构体,并将其子类型化为AbstractValidationRule
,例如。
英文:
The element type of an array constructed with [a, b, ...]
is essentially typejoin(typeof(a), typeof(b), ...)
(ignoring promotion rules), which in this case means the element type is Tuple{DataType, Symbol, Vararg{typeof(convert_name)}}
. This type is not the same as your union type since Vararg
here means any number of typeof(convert_name)
.
You can force the array to have the correct type to make this work:
EitherValidationRule = Union{ValidationRule, ValidationRuleWithConversion}
validate(EitherValidationRule[
(String, :name, convert_name),
(String, :age)
])
But it seems like it would be better to make a proper struct for each type of validation rule and subtype AbstractValidationRule, for instance.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论