Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I add type information to arguments that are functions in Julia?

Tags:

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}
like image 656
MRocklin Avatar asked Jan 10 '14 20:01

MRocklin


People also ask

What is the type of a function in Julia?

Every function in Julia is a generic function. A generic function is conceptually a single function, but consists of many definitions, or methods. The methods of a generic function are stored in a method table. Method tables (type MethodTable ) are associated with TypeName s.

How do functions work in Julia?

A function in Julia is an object that takes a tuple of arguments and maps it to a return value. A function can be pure mathematical or can alter the state of another object in the program.

What is :: In Julia?

A return type can be specified in the function declaration using the :: operator. This converts the return value to the specified type. This function will always return an Int8 regardless of the types of x and y .


2 Answers

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

like image 94
StefanKarpinski Avatar answered Sep 28 '22 01:09

StefanKarpinski


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
like image 41
Cristóvão D. Sousa Avatar answered Sep 28 '22 00:09

Cristóvão D. Sousa