Works:
ModInt(k) = new(mod(k,n))

Doesn't Work:
>ModInt(k,n) = new{n}(mod(k,n))

For an inner constructor, the type parameter is placed on the type 
definition, and so you dont need to specify the type parameter in the 
function (constructor) definition. So for an inner constructor, you can say 
Typ(x) rather than Typ{T}(x) as would have to do for an outer constructor, 
or a normal method. 

Also also don't need to say new{n} in the inner constructor. The `new` is 
part of the type definition, and the compiler knows the parameter of the 
type you're trying to construct. Essentially, the type parameter is 
available at all times within the type definition. You never have to 
declare it in any way. 

So if you want a two parameter constructor, you should create that as an 
outer constructor. 

julia> immutable ModInt{n} <: Integer
           k::Int
           ModInt(k) = new(mod(k,n))
       end

julia> ModInt(k,n) = ModInt{n}(k)
ModInt{n} (constructor with 1 method)

julia> five=ModInt(5,11)
ModInt{11}(5)

Note that all of this the same, regardless of the type of n; whether it is 
a type or a number or a symbol. 

I think you had all of this in your email... I hope putting it in different 
words helps... 


On Wednesday, 2 April 2014 03:14:46 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
>

Reply via email to