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

查看:64
本文介绍了在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:

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

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

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