创建具有参数返回类型的函数
我有一种情况,我想设置一个带有参数返回类型的函数——下面是一个简化的例子。目前似乎这是不可能的 - 使用什么逻辑习语?如何实现合理的代码重用对我来说并不明显。
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。
还要注意在函数签名中使用单例类型。这仅用于限制分派。你可以这样写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)