2

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?

11
  • did you read the part about parametric types being invariant? Commented Jul 7, 2022 at 7:25
  • @Empress.Svetlana Yes. When I add the subtype operator <:, to my understanding I am making sure that the input can be any subtype of Real (?) Commented Jul 7, 2022 at 7:27
  • Right, but Point{Real} isn't a Subtype of Real. When you declare, you have to declare it like this: p = Point{Integer}(12,12) Commented Jul 7, 2022 at 7:30
  • @Empress.Svetlana Thanks. but where in my example above am I assuming that Point{Real} is a subtype of Real? I am only assuming that Integer and Rational are subtypes of Real - or am I misunderstanding something here? Commented Jul 7, 2022 at 7:32
  • :D. You are misunderstanding something here. Commented Jul 7, 2022 at 7:33

1 Answer 1

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)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.