julia - 创建具有参数返回类型的函数
问题描述
我有一种情况,我想设置一个具有参数返回类型的函数——下面是一个简化的例子。这似乎是目前不可能的 - 用什么逻辑成语代替?如何实现合理的代码重用对我来说并不明显。
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)
推荐阅读
- python - Python:使用 RPi GPIO 输入通过 curl 切换智能插头(octoprint 插件 API)
- c++ - c++ 调试不会立即开始运行程序,但重新启动调试器使其再次工作
- php - Laravel : if else 在 Eloquent 创建方法中。我可以这样做吗?
- python - 如何使用 Python 脚本将 JSON 数据转换为蛋白质数据库 (PDB)?
- python - 为什么 numpy.random.choice 不使用算术编码?
- javascript - 由于倾斜滚动,链接图像不起作用
- qt - 不使用 QML 中的简单设置调用保存数组
- javascript - 如何为cordova添加异步/等待支持
- python - SQLAlchemy - 使用事件侦听器更改 FromClause 中的表名
- tensorflow - 初始化 ttpu 时出现 InvalidArgumentError