Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Referencing a type parameter as a function parameter in Julia

Tags:

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.)

like image 426
Alexander Gruber Avatar asked Oct 11 '14 22:10

Alexander Gruber


People also ask

What is :: In Julia?

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 .

What is the type of a function in Julia?

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.

Does Julia pass by reference?

In Julia, values are passed and assigned by reference.


1 Answers

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 ( )
like image 65
StefanKarpinski Avatar answered Nov 20 '22 11:11

StefanKarpinski