朱莉娅:实例化的类型参数 [英] Julia: Instantiated type parameters

查看:159
本文介绍了朱莉娅:实例化的类型参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何定义一个像Array这样具有具体/实例化类型参数的类型?我最初的本能是这样的:

How does one define a type that, like Array, has a concrete/instantiated type parameter? My initial instinct was that it would be like this:

immutable Foo{N::Integer}
  data::Array{Float64, N}
end

但是,这会产生以下错误:

However, this generates the following error:

错误:语法:格式错误的类型参数列表

ERROR: syntax: malformed type parameter list

可接受以下代码:

immutable Foo{N}
  data::Array{Float64, N}
end
Foo{1}([1,2,3])

Foo {1}([1.0,2.0,3.0])

Foo{1}([1.0,2.0,3.0])

但是我一直无法找到任何有关限制参数N类型的指令.我意识到在这种情况下这可能不是严格必要的,但是可以肯定的是它将提供更直观的错误消息,并且应该可行吗?

but I've been unable to find any instructions on restricting the type of the parameter N. I realize that in this case it may not be strictly necessary, but surely it would provide more intuitive error messages and should be possible?

我发现了这样的部分解决方案:

I've found a partial solution like so:

immutable Bar{N}
  data::Array{Int64, N}
  Bar(dat) = (
    typeof(N) <: Integer && N > 0 ?
    new(dat) :
    error("Bar parameter N must be a positive integer"))
end

Bar{1}([1,2,3])

酒吧{1}([1,2,3])

Bar{1}([1,2,3])

Bar{0}([])

错误:条形参数N必须为正整数

ERROR: Bar parameter N must be a positive integer

虽然这解决了手头的问题,但我仍然想知道是否有一种方法可以像我在本文的初始代码片段中尝试的那样预先指定类型参数的实例化类型?

While this solves the problem at hand, I would still be interested in knowing if there's a way to specify the type parameter's instantiated type up front as I tried to do in the initial code fragment in this post?

推荐答案

尽管已经进行了讨论以允许您在顶部尝试使用语法,但目前尚无法限制这样的类型参数.我认为,您想到的在内部构造函数中检查类型参数的解决方案现在被视为最佳实践.

It is currently not possible to restrict type parameters like this, though there has been discussion to allow the syntax that you tried up at the top. I believe that the solution that you came up with of checking the type parameter in an inner constructor is considered the best practice right now.

这篇关于朱莉娅:实例化的类型参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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