Julia: Possible to use only 1 parameter for Vector{S} or S

南笙酒味 提交于 2019-12-25 09:18:28

问题


Is it possible to use only one parameter to do the following

type mytype{S}
  x::Vector{S}
  y::Vector{S} OR y::S
end

the value y should be able to be a vector of type S or just a single element of type S.

The reason I want this is because really I have

y::Dict{Vector{S}, Vector{Int64}}

and when the keys are just 1 element in length this is ugly

y["key"]   #want this
y[["key"]] #must use this

回答1:


I think you need triangular dispatch for this. What you want is

type mytype{S,T<:Union{S,Vector{S}}}
  x::Vector{S}
  y::T
end

This will come in v0.6, see https://github.com/JuliaLang/julia/pull/18457



来源:https://stackoverflow.com/questions/40297172/julia-possible-to-use-only-1-parameter-for-vectors-or-s

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!