在Julia中将类型参数作为函数参数引用
我正在尝试在Julia中创建整数mod p"类型. (我确定已经有一个软件包,这只是个人练习.)
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
定义add时出现错误,表示未定义p.如何从add内部引用p?
I'm getting an error when defining add that says p is not defined. How do I reference p from inside add?
(注意:我可以做类似
type Intp
v::Int8
p
end
function add(a::Intp,b::Intp)
return Intp((a.v + b.v) % a.p,p)
end
,但这将要求p与每个数字一起存储.我觉得这样效率很低,我对归纳起来确实很无效率.我宁愿只为类型指定一次,然后在将该类型的东西作为参数的函数中进行引用.)
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.)
您的第一个示例非常接近,但是您需要在方法名和签名之间包含{p}
,如下所示:
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
否则,您正在编写用于一对Intp{p}
值的方法,其中p
等于p
当前的特定值可能是–在您的情况下,它恰好根本没有任何值,因此错误消息.因此,Julia方法的一般签名是:
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:
- 方法名称
- 类型参数(可选)
{ }
中的( )
中的参数
- method name
- type parameters in
{ }
(optional) - arguments in
( )