Types Julia中的力积分型参数

Types Julia中的力积分型参数,types,julia,Types,Julia,我想定义一个简单的类型来表示n维形状,类型参数包含n julia> struct Shape{n} name::String end julia> square = Shape{2}("square") Shape{2}("square") julia> cube = Shape{3}("cube") Shape{3}("cube") julia> dim(::Shape{n}) where n = n dim (generic

我想定义一个简单的类型来表示
n
维形状,类型参数包含
n

julia> struct Shape{n}
           name::String
       end

julia> square = Shape{2}("square")
Shape{2}("square")

julia> cube = Shape{3}("cube")
Shape{3}("cube")

julia> dim(::Shape{n}) where n = n
dim (generic function with 1 method)

julia> dim(cube)
3
虽然此解决方案确实有效,但它接受非整数值
n
,没有任何问题

julia> Shape{'?'}("invalid")
Shape{'?'}("invalid")
我最初的想法是在
struct
声明中对
n
使用约束。然而,我认为应该实现这一目标的两种方法似乎都不起作用

julia> struct Shape{n} where n <: Int
           name::String
       end
ERROR: syntax: invalid type signature

julia> struct Shape{n<:Int}
           name::String
       end

julia> Shape{2}("circle")
ERROR: TypeError: Shape: in n, expected n<:Int64, got Int64
julia>struct Shape{n}其中n struct Shape{n Shape{2}(“圆”)
错误:TypeError:形状:在n中,应为n个结构形状{n}
形状{n}(名称),其中n形状{2}(“圆”)
错误:MethodError:无法将String类型的对象“转换”为Shape{2}类型的对象
这可能是由于调用构造函数形状{2}(…),
因为类型构造函数会退回到转换方法。
堆栈跟踪:
[1] 形状{2}(::字符串)位于./sysimg.jl:24
我使用的是Julia
0.6.0-rc3.0


如何实现所需的行为?

n
的类型是
Int
,但它不是
数据类型,而
数据类型是内部构造函数的工作方式。您使用了什么代码?@ChrisRackauckas表示歉意;似乎我忘记复制该代码。帖子已经更新。
n
的类型是Int,但是这不是一个
数据类型
,它是
@ChrisRackauckas啊,有意义。(使用类型断言
n::Int
似乎也是一个干净的实现方法。)您介意将您的解决方案作为答案发布吗?还是别担心。类型
Shape{String}
技术上存在,但完全无用。类似地,
数组{12.5,()}
存在,但你不能用它做太多。或者干脆别担心。类型
形状{String}
技术上存在,但完全无用。类似地,
数组{12.5,()}
存在,但你不能用它做太多。
julia> struct Shape{n}
           Shape{n}(name) where n <: Int = new(name)
           name::String
       end

julia> Shape{2}("circle")
ERROR: MethodError: Cannot `convert` an object of type String to an object of type Shape{2}
This may have arisen from a call to the constructor Shape{2}(...),
since type constructors fall back to convert methods.
Stacktrace:
 [1] Shape{2}(::String) at ./sysimg.jl:24
 struct Shape{n}
   name::String
   function Shape{n}(name) where n 
     @assert typeof(n) <: Int
     new(name)
   end
 end
 Shape{2}("square")
 Shape{:hi}("square")