I am declaring a parametric type struct A{L} end
, where L
should be an integer. For example, in NTuple{N,T}
, the N
parameter is restricted to be an integer. What is the recommended way to achieve this behavior on my custom time? I could not find the source code of NTuple
.
I think that NTuple
per se does not check that N
is an integer, Vararg
(which it is aliased to) does.
For struct
s, the recommended solution is to check in the inner constructor, eg
struct A{L}
function A{L}() where L
@assert L isa Integer
new{L}()
end
end
A(L::Integer) = A{L}() # convenience constructor
A(1) # OK
A("a fish") # error
PS: the source of NTuple
is in boot.jl. It is nothing more than
const NTuple{N,T} = Tuple{Vararg{T,N}}
There is no magic. Being able to write such core constructs in Julia lends a certain elegance to the language.
Thanks. If Vararg
is also in Julia, do you know where is the source?
I think that Vararg
is implemented in C.
Hi, I want to achieve the same goal except that L must limited to three integer values 1,2, 3. Is there a way to that using Union{Val{1},Val{2},Val{3}}
. In fact, after create the type I want implement dispatch
on these values like in the constructor of Array{T,N}
Array{T,1}(::UndefInitializer, m::Int) where {T} =
ccall(:jl_alloc_array_1d, Array{T,1}, (Any, Int), Array{T,1}, m)
Array{T,2}(::UndefInitializer, m::Int, n::Int) where {T} =
ccall(:jl_alloc_array_2d, Array{T,2}, (Any, Int, Int), Array{T,2}, m, n)
But Sadly I do not find the definition of Array{T,N} using @edit
Bests
It is not clear to me what you are doing (please open a separate topic with an MWE if you need further help). In any case, validating in the constructor is still the recommended method.
Hi,
Effectively, I enter too abruptly into the discussion. Next time, I will follow the rules for discourse . In addition, my question was not clear. I mixed up two points : restrict the parameter values and enable dispatch respective to the different values of the parameter. Anyway, I found a convienent solution for me and I use your trick for restricting values. Thanks