参数构造函数

发布于 2025-02-13 15:18:23 字数 370 浏览 1 评论 0原文

我遇到了一些问题,了解朱莉娅的参数构造函数的概念。我正在查看Julia文档中的标准示例:

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

就我的理解,这意味着我可以生成一个点数,其输入是真实的,即IE,AbstractFloat,Abstractirrational,...,Integer,Integer,Rational,.. .. 。,statsbase.teststat。

但是,以下两个示例都会导致错误:

Point(Integer(12))
Point(Rational(12))

为什么上述失败鉴于整数和理性都是真实的亚型?

I am having some issues understanding the concept of parametric constructors in Julia. I am looking at the standard example in the Julia docs:

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

To my understanding, this means I can generate a Point-datatype with an input that is subtype of Real, i.e., AbstractFloat, AbstractIrrational, ..., Integer, Rational, ..., StatsBase.TestStat.

However, both of the examples below result in errors:

Point(Integer(12))
Point(Rational(12))

Why does the above fail given that both integer and rational are subtypes of real?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

夏末染殇 2025-02-20 15:18:23

就像在struct定义:


julia> Point{Integer}(12, 12)
Point{Integer}(12, 12)

julia> Point{Rational}(12, 10//3)
Point{Rational}(12//1, 10//3)

所提供的参数是struct IE x中的值 一样和y。如果参数已经是您想要的类型,则可以明确指定类型参数:

julia> Point(12, 6)
Point{Int64}(12, 6)

julia> Point(12.0, 6.0)
Point{Float64}(12.0, 6.0)


julia> Point(12, 6.0) #no automatic type promotion happens though
ERROR: MethodError: no method matching Point(::Int64, ::Float64)
Closest candidates are:
  Point(::T, ::T) where T<:Real at REPL[1]:2
Stacktrace:
 [1] top-level scope
   @ REPL[9]:1

julia> Point{Float64}(12, 6.0) #unless you explicitly specify the type
Point{Float64}(12.0, 6.0)

The type parameter goes inside the curly braces in the constructor call, just like it does in the struct definition:


julia> Point{Integer}(12, 12)
Point{Integer}(12, 12)

julia> Point{Rational}(12, 10//3)
Point{Rational}(12//1, 10//3)

The arguments supplied are the values for the fields of the struct i.e. x and y. If the arguments are already of the type you want, you can leave out explicitly specifying the type parameter:

julia> Point(12, 6)
Point{Int64}(12, 6)

julia> Point(12.0, 6.0)
Point{Float64}(12.0, 6.0)


julia> Point(12, 6.0) #no automatic type promotion happens though
ERROR: MethodError: no method matching Point(::Int64, ::Float64)
Closest candidates are:
  Point(::T, ::T) where T<:Real at REPL[1]:2
Stacktrace:
 [1] top-level scope
   @ REPL[9]:1

julia> Point{Float64}(12, 6.0) #unless you explicitly specify the type
Point{Float64}(12.0, 6.0)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文