Alexander Gruber
Alexander Gruber

Reputation: 519

Referencing a type parameter as a function parameter in Julia

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

Answers (1)

StefanKarpinski
StefanKarpinski

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:

  1. method name
  2. type parameters in { } (optional)
  3. arguments in ( )

Upvotes: 9

Related Questions