首页 > 解决方案 > 创建具有参数返回类型的函数

问题描述

我有一种情况,我想设置一个具有参数返回类型的函数——下面是一个简化的例子。这似乎是目前不可能的 - 用什么逻辑成语代替?如何实现合理的代码重用对我来说并不明显。

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)

任何想法表示赞赏。

标签: julia

解决方案


您可能已经注意到,参数化定义的函数,例如 函数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)

推荐阅读