为什么以下类型声明 and/or 实例化在 Julia 1.0 中不起作用?
Why is the following type declaration and/or instatiation not working in Julia 1.0?
我有圈型
struct Circle{T <: Real}
# radius is a subtype of
# the real number approximation types
R::T
# The center is a named pair of real
# number approximation types
C::NamedTuple{T, T}
end
我想实例化
circles = NamedTuple(
A = Circle(1, ( 1, 1)),
B = Circle(1, ( 2, 2))
)
产生错误
ERROR: LoadError: MethodError: no method matching Circle(::Int64, ::Tuple{Int64,Int64})
Closest candidates are:
Circle(::T<:Real, ::NamedTuple{T<:Real,T<:Real}) where T<:Real
为什么会出现这个错误,我做错了什么?
Named tuples 由名称和元组参数化:
julia> struct Circle{T <: Real}
R::T
C::NamedTuple
Circle(r::T, c::NamedTuple{N,Tuple{T,T}}) where {N, T <: Real} = new{T}(r,c)
end
julia> Circle(1, (a=1, b=2))
Circle{Int64}(1, (a = 1, b = 2))
如果要用元组构造Circle
,可以提供默认映射:
julia> function Circle(r::T, c::Tuple{T,T}) where {T <: Real}
a, b = c
return Circle(r, (a=a, b=b))
end
Circle
julia> Circle(1, (1, 2))
Circle{Int64}(1, (a = 1, b = 2))
如果不需要命名元组,可以使用常规元组:
julia> struct Circle{T <: Real}
R::T
C::Tuple{T, T}
end
julia> Circle(1, (1, 2))
Circle{Int64}(1, (1, 2))
我有圈型
struct Circle{T <: Real}
# radius is a subtype of
# the real number approximation types
R::T
# The center is a named pair of real
# number approximation types
C::NamedTuple{T, T}
end
我想实例化
circles = NamedTuple(
A = Circle(1, ( 1, 1)),
B = Circle(1, ( 2, 2))
)
产生错误
ERROR: LoadError: MethodError: no method matching Circle(::Int64, ::Tuple{Int64,Int64})
Closest candidates are:
Circle(::T<:Real, ::NamedTuple{T<:Real,T<:Real}) where T<:Real
为什么会出现这个错误,我做错了什么?
Named tuples 由名称和元组参数化:
julia> struct Circle{T <: Real}
R::T
C::NamedTuple
Circle(r::T, c::NamedTuple{N,Tuple{T,T}}) where {N, T <: Real} = new{T}(r,c)
end
julia> Circle(1, (a=1, b=2))
Circle{Int64}(1, (a = 1, b = 2))
如果要用元组构造Circle
,可以提供默认映射:
julia> function Circle(r::T, c::Tuple{T,T}) where {T <: Real}
a, b = c
return Circle(r, (a=a, b=b))
end
Circle
julia> Circle(1, (1, 2))
Circle{Int64}(1, (a = 1, b = 2))
如果不需要命名元组,可以使用常规元组:
julia> struct Circle{T <: Real}
R::T
C::Tuple{T, T}
end
julia> Circle(1, (1, 2))
Circle{Int64}(1, (1, 2))