Julia:实例化类型参数 [英] Julia: Instantiated type parameters

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

问题描述

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

The following code is acceptable:

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

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

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?

Edit:

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])

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

Bar{0}([])

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.

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

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