英文:
julia - Why do single functions in vector passed as arguments not work
问题
我有一个演示,演示如何将函数作为参数传递给另一个函数。但并非在所有情况下都有效。
问题在于我得到了:::Vector{typeof(is_valid_wallet_address)}
而不是 Vector{Function}
。
function validate(data::NamedTuple, field::Symbol, validators::Vector{Function})
for validator in validators
validator(data[field])
end
end
function is_valid_wallet_address(address)
# 钱包地址的验证逻辑
end
function is_valid_wallet_signature(signature)
# 钱包签名的验证逻辑
end
data = (wallet_address="123456789", wallet_signature="abcdef")
# 正常工作
validate(data, :wallet_address, [is_valid_wallet_address, is_valid_wallet_signature])
# 不起作用
validate(data, :wallet_address, [is_valid_wallet_address])
validate(data, :wallet_address, [is_valid_wallet_address, is_valid_wallet_address])
希望这对你有所帮助。
英文:
I have a demo here of passing functions as parameters to another function. But its not working in all cases.
The issue is im getting: ::Vector{typeof(is_valid_wallet_address)}
instead of Vector{Function}
function validate(data::NamedTuple, field::Symbol, validators::Vector{Function})
for validator in validators
validator(data[field])
end
end
function is_valid_wallet_address(address)
# Validation logic for wallet address
end
function is_valid_wallet_signature(signature)
# Validation logic for wallet signature
end
data = (wallet_address="123456789", wallet_signature="abcdef")
# works
validate(data, :wallet_address, [is_valid_wallet_address, is_valid_wallet_signature])
# doesn't work
validate(data, :wallet_address, [is_valid_wallet_address])
validate(data, :wallet_address, [is_valid_wallet_address, is_valid_wallet_address])
答案1
得分: 2
这是与协变/逆变/不变子类型相关的相当常见的混淆。Julia 使用不变子类型的概念。一个很好的参考是:https://docs.julialang.org/en/v1/manual/types/#man-parametric-composite-types。
要克服这个困难,可以定义函数validate
,使其接受任何Function的子类型,然后所有的调用都会按预期工作:
function validate(data::NamedTuple, field::Symbol, validators::Vector{<:Function})
for validator in validators
validator(data[field])
end
end
请注意<:
在Function
之前。
英文:
This is a rather common confusion related to contra-variant/covariant/invariant subtypes. Julia goes with the invariant subtyping idea. A good reference is: https://docs.julialang.org/en/v1/manual/types/#man-parametric-composite-types.
To get over this difficulty, the function validate
can be defined to take any subtype of Function and then all the calls work as expected:
function validate(data::NamedTuple, field::Symbol, validators::Vector{<:Function})
for validator in validators
validator(data[field])
end
end
Note the <:
before Function
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论