Question

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}
Was it helpful?

Solution

Not currently. We may add something along those lines in the future, however.

OTHER TIPS

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top