在 Julia 中将类型参数引用为函数参数 [英] Referencing a type parameter as a function parameter in Julia

查看:18
本文介绍了在 Julia 中将类型参数引用为函数参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在 Julia 中创建一个integer 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?

(注意:我可以做类似的事情

(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

但这需要 p 与每个数字一起存储.我觉得这会效率低下,而且我会考虑泛泛而谈,这将是非常低效的.我宁愿 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} 值编写方法,其中 pp 的当前特定值可能是 - 在您的情况下,这恰好没有任何价值,因此会出现错误消息.所以 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:

  1. 方法名称
  2. { } 中输入参数(可选)
  3. ( )中的参数
  1. method name
  2. type parameters in { } (optional)
  3. arguments in ( )

这篇关于在 Julia 中将类型参数引用为函数参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆