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.)
A return type can be specified in the function declaration using the :: operator. This converts the return value to the specified type. This function will always return an Int8 regardless of the types of x and y .
Function is an abstract type. So for example Vector{Function} is like a Vector{Any} , or Vector{Integer} : Julia just can't infer the results.
In Julia, values are passed and assigned by reference.
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)( )
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With