我正在编写一个函数来搜索集合并收集一些用户提供的函数的输出f并g应用于它找到的东西.
function search_map_collect(f::Function, g::Function)
output = []
# searching through the collection
# oh look we found an x and a y
push!(output, f(x, y))
# whoa, we even found a z
push!(output, g(x, y, z))
# end loopy stuff
return output
end
Run Code Online (Sandbox Code Playgroud)
在编写函数时,输出将始终具有类型Array{Any,1},因为这是空数组的类型.但是,通常会出现f并g始终返回相同类型的值的情况T.在这种情况下,内置函数map会返回类型的输出Array{T,1},我希望我的函数表现相同.有一个很好的方法来做到这一点?
如果Julia支持带签名的函数类型,那么这很容易.不幸的是,事实并非如此.
如果我可以很容易地预测何时f或g将首先应用,我可以将输出数组初始化为
output = [f(x_first, y_first)]
Run Code Online (Sandbox Code Playgroud)
设置类型.不幸的是,我无法预测第一个应用程序.
我意识到我可以做一些可怕的事情
function complicated_collect(f::Function, g::Function)
output = Union{}[]
# searching through the collection
# oh look we found an x and a y
if isempty(output)
output = [f(x, y)]
else
push!(output, f(x, y))
end
# whoa, we even found a z
if isempty(output)
output = [g(x, y, z)]
else
push!(output, g(x, y, z))
end
# end loopy stuff
return output
end
Run Code Online (Sandbox Code Playgroud)
但这会使代码的可读性降低,而且效率也不高.
如果在调用函数时知道返回类型,则可以将其添加为参数.
function test1(t::Type, f::Function)
output = t[]
for x in 1:5
push!( output, f(x) )
end
output
end
test1( Float64, exp )
@code_warntype test1(exp)
Run Code Online (Sandbox Code Playgroud)
由于它是类型稳定的,它应该比使用找到的第一个元素的类型更有效.
| 归档时间: |
|
| 查看次数: |
137 次 |
| 最近记录: |