Reputation: 519
I'm trying to make an "integer mod p" type in Julia. (I'm sure there's already a package for this, it's just a personal exercise.)
type Intp{p}
v::Int8
end
function add(a::Intp{p},b::Intp{p})
return Intp{p}((a.v + b.v) % p)
end
I'm getting an error when defining add that says p is not defined. How do I reference p from inside add?
(Note: I could do something like
type Intp
v::Int8
p
end
function add(a::Intp,b::Intp)
return Intp((a.v + b.v) % a.p,p)
end
but this would require that p be stored with every single number. I feel like this would be inefficient, and I have my mind on generalizations where it would be really inefficient. I would rather p just be specified once, for the type, and referenced in functions that take things of that type as arguments.)
Upvotes: 6
Views: 427
Reputation: 33249
Your first example is very close, but you need to include {p}
between the method name and the signature like this:
function add{p}(a::Intp{p},b::Intp{p})
return Intp{p}((a.v + b.v) % p)
end
Otherwise, you are writing a method for a pair of Intp{p}
values where p
is whatever the current specific value of p
may be – which, in your case, happens to be no value at all, hence the error message. So the general signature of a Julia method is:
{ }
(optional)( )
Upvotes: 9