Can I add type information to arguments that are functions?
Consider the following example:
function f{T} (func, x::Int)
output = Dict{Int, Any}()
output[x] = func(x)
return output
end
I don't like that I have to say Any
for the value type of the dictionary. I'd much rather do the following:
function f{T} (func::Function{Int->T}, x::Int)
output = Dict{Int, T}()
output[x] = func(x)
return output
end
Can I provide type hints of functions like this? I kind of want to say the following
f :: (Int -> T), Int -> Dict{Int, T}
Not currently. We may add something along those lines in the future, however.
This is not an answer to the main question, but more a really ugly workaround the Any
in the Dict
issue:
function f(func, x::Int)
T = code_typed(func, (Int,))[1].args[3].typ
output = Dict{Int, T}()
output[x] = func(x)
return output
end
That is probably not efficient and will probably work only on simple cases (which do not even include anonymous functions) like
>>> g(x) = x*2
>>> typeof(f(g, 1234))
Dict{Int64,Int64}
>>> h(x) = x > zero(x) ? x : nothing
>>> typeof(f(h, 1234))
Dict{Int64,Union(Int64,Nothing)}
EDIT:
This works better:
function f(func, x::Int)
[x => func(x)]
end
>>> dump( f(x->2x, 3) )
Dict{Int64,Int64} len 1
3: Int64 6