我有一种情况,我想设置一个具有参数返回类型的函数——下面是一个简化的例子。这似乎目前是不可能的 - 应该使用什么逻辑成语呢?如何实现合理的代码重用对我来说并不明显。
struct Output{T <: Number}
other_details::String # lots of stuff here
numeric_output::T
end
function get_output{T <: Number}(input)::Output{T}
transformed_input = input
# Do stuff to transformed_input
Output{T}(
"lots of data",
transformed_input
)
end
input = 1::Int64
get_output{Float64}(input)
任何想法表示赞赏。
最佳答案
您可能已经注意到,参数化定义的函数,例如像 foo{T}(x)
这样的函数,只有当它们是一个类型(已经被定义)的构造函数时才能被定义。您可以做的是将所需的输出类型作为函数参数,如下所示:
struct Output{T <: Number}
other_details::String
numeric_output::T
end
function get_output(::Type{T}, input) where {T <: Number}
Output("lots of data", T(input))
end
julia> get_output(Float64, 1)
Output{Float64}("lots of data", 1.0)
请注意,文字 1
已经是一个整数。无需编写 1::Int64
。
另请注意 singleton type 的使用在函数签名中。这仅用于限制调度。您可以像这样编写 get_output
,它会正常工作:
get_output(T, input) = Output("lots of data", T(input))
顺便说一句,我强烈建议不要这样做,但有可能作弊,因为 Julia 编译器不强制构造函数实际返回它们应该构造的类型的实例:
struct Output{T <: Number}
other_details::String
numeric_output::T
end
struct get_output{T} end
function get_output{T}(input) where {T <: Number}
Output("lots of data", T(input))
end
julia> get_output{Float64}(1)
Output{Float64}("lots of data", 1.0)
关于julia - 创建具有参数返回类型的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66683629/