Inner constructor functions can also have type parameters but they don't
have to be necessarily related to the parameter of the type itself.
E.g.,
immutable ModInt{n} <: Integer
k::Int
function ModInt{T}(k::T)
println("n=$n k=$k T=$T")
new(mod(k,n))
end
end
julia> ModInt{3}(5.0)
n=3 k=5 T=Float64
ModInt{3}(2)
In this case, the *3* in the constructor call is referred to *n* (the type)
and not to *T*.
I had little hard time until I understood all of this :)
On Wednesday, April 2, 2014 9:52:25 AM UTC+1, Cristóvão Duarte Sousa wrote:
>
> And let me add that, as far as I know, a call as ModInt{i}(...) is always
> a call to a inner constructor of the type ModInt{i}. We cannot call
> external constructors like that.
>
> Moreover, external constructors seem be be ordinary generic functions and
> one can even do stuff unrelated to the type (somehow also true for inner
> constructors):
> julia> ModInt{n}(a::Array{Float64, n}) = "stuff unrelated to ModInt type"
> julia> ModInt([1., 2.])
> "stuff unrelated to ModInt type"
> While this
> julia> ModInt{1}([1., 2.])
> no method convert(Type{Int64}, Array{Float64,1})
> is just a (unsuccessful) call to the inner constructor of ModInt{1}.
>
> On Wednesday, April 2, 2014 3:14:46 AM UTC+1, Leah Hanson wrote:
>>
>> I do not understand (numeric?) type parameters, and the manual has not
>> enlightened me.
>> As an exercise, I'm trying to write a ModInt type.
>>
>> I found https://github.com/JuliaLang/julia/blob/master/examples/modint.jl,
>> which does work.
>>
>> However, I don't understand what the difference is between the version
>> used there and the version I was trying.
>>
>> The example:
>> ~~~
>>
>> immutable ModInt{n} <: Integer
>>
>> k::Int
>>
>>
>> ModInt(k) = new(mod(k,n))
>>
>> end
>>
>> ~~~
>>
>> My failing attempt:
>> ~~~
>> immutable ModInt{n} <: Integer
>> k::Int
>> ModInt(k,n) = new{n}(mod(k,n))
>> end
>> ~~~
>>
>> At first, I was confused about how the example knows what `n` is in the
>> constructor. I realize that this is constructed as `ModInt{2}(5)`, but the
>> `n` is just magically shared?
>> This part is clarified in the manual, if you assume that numeric type
>> parameters work exactly as normal ones. (
>> http://docs.julialang.org/en/release-0.2/manual/constructors/#parametric-constructors
>> )
>>
>> In the my attempted version, the type is accepted, but constructing
>> things doesn't work:
>> ~~~
>> julia> five = ModInt(5,2)
>> ERROR: no method ModInt{n}(Int64, Int64)
>>
>> julia> five = ModInt{2}(5)
>> ERROR: no method ModInt{2}(Int64)
>> ~~~
>>
>> The second instantiation works for the example, which is what I expected.
>> However, I still don't understand why the first instantiation doesn't work
>> for my version. What does the compiler think is going on?
>>
>> Thanks,
>> Leah
>>
>