Julia: why do parametric types have external constructors?

The following works:

type TypeA x :: Array y :: Int TypeA(x :: Array ) = new(x, 2) end julia> y = TypeA([1,2,3]) TypeA([1,2,3],2) 

It does not mean:

 type TypeB{S} x :: Array{S} y :: Int TypeB{S}( x:: Array{S} ) = new(x,2) end julia> y = TypeB([1,2,3]) ERROR: `TypeB{S}` has no method matching TypeB{S}(::Array{Int64,1}) 

To make the second case work, you need to declare the constructor outside the type declaration. This is a bit undesirable. My question is why this problem exists from the point of view of Julia-design, so I can better talk about the type of Julia system.

Thanks.

+8
julia-lang
source share
1 answer

It works:

 type TypeB{S} x::Array{S} y::Int TypeB(x::Array{S}) = new(x,2) end TypeB{Int}([1,2,3]) 

which I found out after reading the manual , but I must admit that I do not understand internal constructors very well, especially for parametric types, I think this is because you actually define a type family, so the internal constructor is only reasonable for each individual type so you need to specify {Int} to tell which type you want. You can add an external constructor to simplify it, i.e.

 type TypeB{S} x::Array{S} y::Int TypeB(x::Array{S}) = new(x,2) end TypeB{S}(x::Array{S}) = TypeB{S}(x) TypeB([1,2,3]) 

I think it would be nice to pick it up on Julia's problems page, because I feel that this external helper assistant constructor can be provided by default.

EDIT: This Julie question points to problems with providing an external default constructor.

+8
source share

All Articles