gpt4 book ai didi

julia - <: in julia?是什么意思

转载 作者:行者123 更新时间:2023-12-03 23:59:06 24 4
gpt4 key购买 nike

谁能帮我解决这个代码:

struct GenericPoint{T<:Real}
x::T
y::T
end

<: 是什么意思在 {T<:Real}在朱利亚朗?

最佳答案

首先让我说punctuation手册页是搜索此类运算符的便捷方式,否则使用搜索引擎很难找到这些运算符。在 <: 的具体情况下,我们找到此页面,以及 essential operators 的相关文档.

有(至少)3 个上下文,A <: B可能会被使用,并且在所有这些中都表达了 A 的想法。是 B 的子类型.

  1. 作为谓词,A <: B返回 true当且仅当所有 A 类型的值也是 B 类型:
julia> Int <: Number
true

julia> Int <: AbstractString
false
  1. 在类型定义中,这声明新定义的类型是现有(抽象)类型的子类型:
# `Foo` is declared to be a subtype of `Number`
struct Foo <: Number
end
  1. 作为类型参数约束(如您的示例中),T <: Real表示类型参数 T 的想法可以是 Real 的任何子类型:
julia> struct GenericPoint{T<:Real}
x::T
y::T
end

# Works because 1 and 2 are of type Int, and Int <: Real
julia> GenericPoint(1, 2)
GenericPoint{Int64}(1, 2)

# Does not work because "a" and "b" are of type String,
# which is not a subtype of Real
julia> GenericPoint("a", "b")
ERROR: MethodError: no method matching GenericPoint(::String, ::String)
Stacktrace:
[1] top-level scope at REPL[5]:1

请注意,类型参数约束的使用不仅限于参数类型的定义,还适用于函数/方法定义:

julia> foo(x::Vector{T}) where {T<:Number} = "OK"
foo (generic function with 1 method)

# OK because:
# - [1,2,3] is of type Vector{Int}, and
# - Int <: Number
julia> foo([1, 2, 3])
"OK"

# Incorrect because:
# - ["a", "b", "c"] is of type Vector{String}, but
# - String is not a subtype of Number
julia> foo(["a", "b", "c"])
ERROR: MethodError: no method matching foo(::Array{String,1})

关于julia - <: in julia?是什么意思,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64915738/

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