“julia – 函数不接受包含函数的元组作为参数”

huangapple go评论54阅读模式
英文:

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,&lt;: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 -&gt; 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.

huangapple
  • 本文由 发表于 2023年6月9日 11:34:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/76437047.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定