我可以在 Julia 中专门化类型定义吗? [英] Can I specialize type definitions in Julia?

查看:17
本文介绍了我可以在 Julia 中专门化类型定义吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Julia 的参数类型确实定义了一系列包含不同内存布局的类型.我想知道这是否也适用于复合类型中的名称和字段数?一个简单的例子是这样的:

Julia's parametric types really define a family of types containing different layout in memory. I was wondering if this works also for the names and number of fields in a composite type? A simple example would be something like:

type mytype{Float64}
    a::Float64
    b::Float64
end

type mytype{Int64}
    a::Int64
end

这给了我重新定义 mytype 的错误.

This gives me an error for redefining mytype.

在这里,如果 mytype 的类型参数是 Float64,我想要两个字段,如果它的 Int64 则只有一个字段.(其实我想要的比较复杂,但这是一个基本的例子).可以想象上面有抽象类型和<:等.

Here, I want to have two fields if mytype's type parameter was Float64 and just one if its Int64. (Actually what I want is more complicated, but this is a basic example). One could imagine having abstract types and <:, etc in the above.

我意识到这在其他语言中可能是不可能的,但在我看来,编译器应该能够像函数专门化一样解决这个问题.毕竟,真实(已编译)代码将涉及具体类型,编译器将知道所有内容.(对于真正的动态类型,在这种情况下可能需要额外的封装层?)

I realize this might not be possible in other languages, but to me it seems the compiler should be able to figure this out much the same way functions can be specialized. After all, real (compiled) code will involve concrete types and everything will be known by the compiler. (for truly dynamical types, perhaps an additional layer of encapsulation would be required in this case?)

也许有不同/更好的方法来获得类似的结果?

Perhaps there is a different/better way of achieving similar results?

推荐答案

目前无法实现,但在问题 #8472.只要您注意分组的 mytype 构造函数是类型稳定的,塞巴斯蒂安的答案就是一个合理的解决方法.有关更完整的示例,请参阅 ImmutableArrays.jl 如何以编程方式围绕抽象 ImmutableArray轨迹.

This is currently not possible, but the feature has been speculatively proposed as "generated types" in issue #8472. Sebastian's answer is a reasonable work around so long as you take care that the grouped mytype constructor is type-stable. For a more complete example, see how ImmutableArrays.jl programmatically defines a group of types around the abstract ImmutableArray locus.

这篇关于我可以在 Julia 中专门化类型定义吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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