julia – 为什么向量中的单个函数作为参数无法运行

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

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{&lt;:Function})
    for validator in validators
        validator(data[field])
    end
end

Note the &lt;: before Function.

huangapple
  • 本文由 发表于 2023年6月6日 01:06:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/76408612.html
匿名

发表评论

匿名网友

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

确定