gpt4 book ai didi

arrays - Julia:函数参数 - 数组的类型规范

转载 作者:行者123 更新时间:2023-12-02 03:09:27 24 4
gpt4 key购买 nike

我似乎错过了有关多个调度+参数类型的一些内容:

Integer 是所有整数类型的抽象父类(super class)型,因此方法 f(arg::Integer) 按预期工作:

f(arg::Integer) = println("an integer")
# f(42) prints "an integer"
# f(UInt8(42)) prints "an integer"

但是如果我尝试使用一维整数数组作为参数类型进行相同的操作,julia 会给出错误消息:

f(arg::Array{Integer, 1}) = println("an array with integers")
f(arg::Array{Signed, 1}) = println("an array with signed integers")
# f([1,2,3]) gives "no method matching f(::Array{Int64,1})..."

知道这里出了什么问题吗? – 提前致谢!

最佳答案

您遇到了参数类型不变性,这是手册中漂亮的橙色警告框 here .

引用相关部分:

Concrete Point types with different values of T are never subtypes of each other:

julia> Point{Float64} <: Point{Int64}
false

julia> Point{Float64} <: Point{Real}
false

Warning

This last point is very important: even though Float64 <: Real we DO NOT have Point{Float64} <: Point{Real}.

对于您的示例,您需要:

f(arg::Array{<:Integer, 1}) = println("an array with integers")
# Alternatively f(arg::Array{T, 1}) where T <: Integer = println("an array with integers")
f(arg::Array{Signed, 1}) = println("an array with signed integers")

第一个方法是一般整数数组的后备方法,第二个方法可以使用特定类型 Array{Signed, 1} 调用:

julia> f([1,2,3])
an array with integers

julia> f(Array{UInt8, 1}([1,2,3]))
an array with integers

julia> f(Array{Signed, 1}([1,2,3]))
an array with signed integers

关于arrays - Julia:函数参数 - 数组的类型规范,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58092899/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com