Reference to type parameter as function parameter in Julia

I am trying to create an "integer mod p" in Julia. (I am sure there is already a package for this, this is just a personal exercise.)

type Intp{p} v::Int8 end function add(a::Intp{p},b::Intp{p}) return Intp{p}((av + bv) % p) end 

I get an error when defining add that says p is undefined. How to set p link from inside?

(Note: I could do something like

 type Intp v::Int8 p end function add(a::Intp,b::Intp) return Intp((av + bv) % ap,p) end 

but this requires p to be stored with each number. I feel that it will be ineffective, and I mean generalizations where it will be really ineffective. I would prefer that p is simply indicated once for the type and refers to functions that take things of this type as arguments.)

+5
source share
1 answer

Your first example is very close, but you need to include {p} between the method name and signature as follows:

 function add{p}(a::Intp{p},b::Intp{p}) return Intp{p}((av + bv) % p) end 

Otherwise, you are writing a method for a pair of Intp{p} values, where p is what may be the current specific value of p - which in your case does not matter at all, hence the error message. Thus, the general signature of the Julia method:

  • method name
  • enter parameters { } (optional)
  • arguments to ( )
+7
source

Source: https://habr.com/ru/post/1204488/


All Articles